1+ /*********************************************************************************
2+ * (Pattern matching) Write a program that prompts the user to enter two strings *
3+ * and tests whether the second string is a substring of the first string. (Don’t *
4+ * use the indexOf method in the String class.) Analyze the time complexity of *
5+ * your algorithm. *
6+ *********************************************************************************/
7+ import java .util .Scanner ;
8+
9+ public class Exercise_22_04 {
10+ public static void main (String [] args ) {
11+ Scanner input = new Scanner (System .in );
12+
13+ // Prompt the user to enter two strings
14+ System .out .print ("Enter a string s1: " );
15+ String s1 = input .nextLine ();
16+ System .out .print ("Enter a string s2: " );
17+ String s2 = input .nextLine ();
18+
19+ int index = -1 ; // Index of sub string
20+ int count = 0 ; // Count matching characters
21+ boolean matched = false ;
22+
23+ // tests whether the second string
24+ // is a substring of the first string
25+ for (int i = 0 ; i < s1 .length (); i ++) {
26+ if (s1 .charAt (i ) != s2 .charAt (count )){
27+ count = 0 ;
28+ }
29+
30+ if (s1 .charAt (i ) == s2 .charAt (count )) {
31+ if (count == 0 )
32+ index = i ;
33+ count ++;
34+ }
35+
36+ if (count == s2 .length ()) {
37+ matched = true ;
38+ break ;
39+ }
40+ }
41+
42+ // Display result
43+ if (matched )
44+ System .out .println ("matched at index " + index );
45+ else
46+ System .out .println ("\" " + s2 +
47+ "\" is not a substring of \" " + s1 + "\" " + "." );
48+ }
49+ }
0 commit comments