I'm trying to find a part of str1 inside str2 (two strings). Currently I have a working program however it's not exactly working correctly or using the correct logic in my opinion.
public static void main(String[] params) {
String str1 = "blis";
String str2 = "grisdisbliszis";
//String str2 = "adasdsfgsdfdcx";
System.out.println(isCommonSubstring(str1, str2));
}
public static boolean isCommonSubstring(String str1, String str2) {
char char1, char2;
boolean match = true;
String check = "";
for(int i = 0; i < str1.length(); i++) {
char1 = str1.charAt(i);
for(int j = 0; j < str2.length(); j++) {
char2 = str2.charAt(j);
if(char1 == char2) {
check += char1;
System.out.println("Matched!: "+str1.charAt(i)+"[Char "+i+"] <==> " // DEBUG
+str2.charAt(j)+"[Char "+j+"]"); // DEBUG
break; // Break because we've found our first match and we need to check others
}
}
}
System.out.println(check+" || "+str1);
if(check.equals(str1)) match = true;
else match = false;
return match;
}
This may work but if I turn these two strings around it no longer works.
How can I improve the logic of finding a match? I tried to possibly use substring() somehow however I'm not sure how to fit it inside.
The solution I'm thinking of is possibly making if statements to compare lengths and make str2 the longer length so it's always longer and does not cause errors. But is this a decent solution?
I can only use length, substring and charAt.
isSubstringis misleading, because it leads the readers to think your method is checking if str1 is a substring of str2.