Write a recursive method named contains with the following header:
public static boolean contains(String haystack, String needle)
The method should return true if needle is contained within haystack and false if needle is not in haystack . For example,
contains("Java programming", "ogr") should return true
contains("Java programming", "grammy") should return false
You are not allowed to use the substring method to find a match.
PROGRAM CODE:
public class Main {
public static boolean contains(String haystack, String needle) {
if (needle.length() == 0) {
return true; // An empty string is always contained within any string
}
if (haystack.length() < needle.length()) {
return false; // The needle is longer than the remaining haystack, so it can't be found
}
if (haystack.charAt(0) == needle.charAt(0)) {
// The first characters match, check the remaining characters
if (contains(haystack.substring(1), needle.substring(1))) {
return true; // Found a match
}
}
// Move to the next character in the haystack and try again
return contains(haystack.substring(1), needle);
}
public static void main(String[] args) {
String haystack = "Java programming";
String needle1 = "ogr";
String needle2 = "grammy";
System.out.println(contains(haystack, needle1)); // true
System.out.println(contains(haystack, needle2)); // false
}
}
OUTPUT OF THE PROGRAM CODE:
true
false