Please note, this is a STATIC archive of website www.w3resource.com from 19 Jul 2022, cach3.com does not collect or store any user information, there is no "phishing" involved.
w3resource

Java String Exercises: Check whether a prefix string creates using the first specific characters in a given string appears somewhere else in the string

Java String: Exercise-74 with Solution

Write a Java program to check whether a prefix string creates using the first specific characters in a given string, appears somewhere else in the string.

Sample Solution:

Java Code:

import java.util.*;
public class Main
{
public boolean nChrStringSomewhere (String stng, int n_chr) 
{
  int len = stng.length();
  String pre_str = stng.substring(0,n_chr);
  for (int i = n_chr; i < len; i++) 
  {
    if(n_chr+i <= len) 
	{
      if (pre_str.equals(stng.substring(i,n_chr+i)))
        return true;
    }
  }
  return false;
}
public static void main (String[] args)
    {
      Main m= new Main();
      String str1 =  "MrsJemsMrsam";
      int n=3;
	  String prechr=str1.substring(0,n);
      System.out.println("The given string is: "+str1);
      System.out.println("The prefix string length is: "+n);
      System.out.println("Is '"+ prechr+"' appear else where in the string? "+m.nChrStringSomewhere(str1,n));
	  }
}

Sample Output:

The given strings is: MrsJemsmrsam
The prefix string length is: 3
Is 'Mrs' appear else where in the string? false

The given string is: MrsJemsMrsam
The prefix string length is: 3
Is 'Mrs' appear else where in the string? true

Pictorial Presentation:

Java String Exercises: Check whether a prefix string creates using the first specific characters in a given string appears somewhere else in the string.

Flowchart:

Flowchart: Java String Exercises - Check whether a prefix string creates using the first specific characters in a given string appears somewhere else in the string.

Java Code Editor:

Improve this sample solution and post your code through Disqus

Previous: Write a Java program to check whether a substring appears before a period(.) within a given string.
Next: Write a Java program to check whether a given substring presents in the middle of another given string. Here middle means difference between the number of characters to the left and right of the given substring not more than 1.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Java: Tips of the Day

How to sort an ArrayList?

Collections.sort(testList);
Collections.reverse(testList);

That will do what you want. Remember to import Collections though!

Ref: https://bit.ly/32urdSe