I have two strings str, str2. Both strings have spaces. I used contains method but it does not fit here because it checks only the exact characters. How to check whether one string is a substring or not here.
I have implemented it using the below code. So the function in the code prints true if String "FOO BAR" is present in the original String.
public static void main(String[] args) {
String str = "FOO BAR";
String str1 = "FOO T BAR";
String orignialString;
String stringToMatch;
if (str1.length() > str.length()) {
orignialString = str1;
stringToMatch = str;
} else {
orignialString = str1;
stringToMatch = str;
}
boolean flag = false;
String[] stringarr = stringToMatch.split(" ");
for (int i = 0; i < stringarr.length; i++) {
if (orignialString.contains(stringarr[i])) {
flag = true;
} else {
flag = false;
break;
}
}
System.out.println("IS SUBSTRING---> " + flag);
}
I'm looking out for more clean short code using Pattern Matcher / REGEX.