Write a method public boolean subString(String str1, String str2) that returns t
ID: 663342 • Letter: W
Question
Write a method public boolean subString(String str1, String str2) that returns true if stri is a substring of str2. and false otherwise. For example, subString(abc, abcd) returns true, but subString(de, abcd) and subString(ac, abcd) both return false. Implement the method from first principles. That is, you may use only the Java String library methods charAt and length. No other String methods (such as indexOf) may be used. Write 3 (three) Junit4 assertEquals statements to test your subString method. Your tests should cover different cases for the method.Explanation / Answer
I have defined one class name Substring1 and then defined subString function to find the substring from the strings passed to the function and i have defined one user defined function which is recursive in nature and will help in output of this function.And the return type of this function is boolean as defined in the above question and respective comments have mentioned in the following code.Please refer to the below code mentioned.
public class Substring1 {
public static void main(String[] args) {
System.out.println(" Result = "
+ findMe(" findMe", "Can you findMe from this String?"));
}
public static boolean subString(String str1, String str2) {
boolean foundme = false;
int max = str2.length() - str1.length();
// Java's Default "contains()" Method
System.out.println(str2.contains(str1) ? "str2.contains(str1) Substring found"
: "str2.contains(str1) Substring not found..");
// Implementing user defined method with Recursion
checkrecusion: for (int i = 0; i <= max; i++) {
int n = str1.length();
int j = i;
int k = 0;
while (n-- != 0) {
if (str2.charAt(j++) != str1.charAt(k++)) {
continue checkrecusion;
}
}
foundme = true;
break checkrecusion;
}
System.out.println(foundme ? " Result Found"
: " No Result found");
return foundme;
}
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.