1. write the method boolean search (String str, String str2), which should retur
ID: 3631590 • Letter: 1
Question
1. write the method boolean search (String str, String str2), which should return true if str2 is found somewhere inside str, and false otherwise. all the charachters of str2 have to appear adjacent and in order in str for true to be returned. for example, search ("educate", "cat") would return true, but search ("decimate", "math") would return false, as would search("decimate", "cat")
DO NOT USE THE STRING CLASS METHOD OF INDEXOF
2. Java's String library class has a substring method, but suppose it didnt exitst. write the method String substring(String str, int begin, int end) which should return a new string that contains all of the charachters between positions begin and end of its parameter string str (including the one at positions begin, but NOT the one at position end). the first charachter of a string is at position 0. for example, substring ("educate", 3, 6) would return the string "cat"
Explanation / Answer
public boolean search(String str, String str2)
{
// iterate through indices in str
for(int i = 0; i <= str.length() - str2.length(); i++)
// check if the substring of str, starting at the current index of str, matches str2
if(str.substring(i, i+str2.length()).equals(str2))
return true;
return false;
}
public String substring(String str, int begin, int end)
{
String output = "";
// iterate through selected indices
for(int i = begin; i < end; i++)
output += str.charAt(i);
return output;
}
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.