w3resource
Java Programming Exercies

Java String Exercises: Return whether a prefix string made of the first N specific characters of the string appear somewhere else in the string

Java String: Exercise-74 with Solution

Write a Java program to return whether a prefix string made of the first N specific characters of the string appear 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

Flowchart:

Flowchart: Java String Exercises - Return whether a prefix string made of the first N specific characters of the string appear somewhere else in the string

Java Code Editor:

Improve this sample solution and post your code through Disqus

Previous: Write a Java program to return true if the given string contains an appearance of 'abc' but not directly a period(.)and followed by.
Next: Write a Java program to check whether a string 'abc' in the middle of a given string. Here middle means the number of character to the left and right of the substring 'abc' must differ by at most one.

What is the difficulty level of this exercise?



New Content: Composer: Dependency manager for PHP, R Programming