Reputation: 135
I would like to check whether a string contains a sub list.
For example, str1 = "qwertyuiop"
and str2 = "tyu"
returns true
.
I have written an iterative
method.
public static boolean checkString(String str1, String str2) {
for (int i=0; i<str2.length(); i++) {
int j = 0;
for (; j<str1.length()&& str1.charAt(j)!=str2.charAt(i); j++) {
}
if (j== str1.length())
return false;
}
return true;
}
I am trying changing it to recursive
method but not sure how as there are two nested for loops.
Thank you in advance.
Upvotes: 1
Views: 79
Reputation: 26077
public class Test {
public static void main(String[] args) {
System.out.println(isSubstring("ankur", "ku"));
}
public static boolean isSubstring(String str1, String str2) {
if ((str1 == null) || (str2 == null) || str1.isEmpty()) {
return false;
} else if (str1.startsWith(str2)) {
return true;
} else {
return isSubstring(str1.substring(1), str2);
}
}
}
Upvotes: 1
Reputation: 201447
I suggest you focus on other activities. Java already includes a function to do what you are implementing, and that is String.contains(CharSequence)
like
if (str1.contains(str2)) { // <-- wherever you would have called "checkString"
// ...
}
Upvotes: 3