3.4k views
0 votes
Complete the static method stringSearch, which returns a String that tells where the first occurrence of the characters (chr) were found ("The characters were found at ____ index.") or it says, "Those characters could not be found." The String to be searched (phrase) and the characters that are being looked for (chr) are passed in as arguments. (9 points) public static String stringSearch (String phrase, String chr) { ** Complete the code ** }

2 Answers

6 votes

Final answer:

You need to use the 'indexOf' method within the 'stringSearch' function to find a substring within a larger string and return an appropriate message based on whether the substring is found.

Step-by-step explanation:

The question involves completing a static method stringSearch within the context of programming - likely a Computer Science or Programming class project. The method should search for the first occurrence of a substring (chr) within a larger string (phrase) and return a statement indicating the index at which the substring was found or that it was not found at all. If found, the result should be "The characters were found at ____ index." If not found, the result should be "Those characters could not be found."

To solve this, we would implement the Java method like so:

public static String stringSearch(String phrase, String chr) {
int index = phrase.indexOf(chr);
if (index != -1) {
return "The characters were found at " + index + " index.";
}

return "Those characters could not be found.";
}

This code uses the indexOf method which is a standard method in the Java programming language for finding the index of a substring within a larger string. The indexOf method returns the index of the first occurrence of the substring or -1 if the substring does not exist within the string.

User Illorian
by
4.2k points
1 vote
Well can't do it for you but try using that phrase argument with string compare functionality
User Intgr
by
4.3k points