I am developing a Java program that prompts a user to enter two strings and tests whether the second string is a substring of the first string.
Actual:
Enter a string s1:Welcome to Java
Enter a string s2:come
No match%
Expected
Enter a string s1:Welcome to Java
Enter a string s2:come
matched at index 3
My attempt
import java.util.*;
public class Test2 {
public static void main(String args[]){
Scanner input = new Scanner(System.in);
System.out.print("Enter a string s1:");
String s1 = input.nextLine();
System.out.print("Enter a string s2:");
String s2 = input.nextLine();
int index = matched(s1, s2);
if(index > 0)
System.out.printf("matched at index %d",matched(s1, s2));
else
System.out.printf("No match");
}
public static int matched(String s1, String s2){
return indexOfDifference(s1,s2);
}
public static int indexOfDifference(String str1, String str2) {
if (str1 == str2) {
return -1;
}
if (str1 == null || str2 == null) {
return 0;
}
int i;
for (i = 0; i < str1.length() && i < str2.length(); ++i) {
if (str1.charAt(i) != str2.charAt(i)) {
break;
}
}
if (i < str2.length() || i < str1.length()) {
return i;
}
return -1;
}
}
How can I implement the matching algorithm?