AP® Computer Science A

Free Version

Upgrade subject to access all content

Moderate

Sequential Search of Characters in a String

APCSA-KG6X42

Which of the following methods correctly returns the index of the first occurrence of searchFor in the string phrase, and if searchFor is not found, the method returns -1?

I.
public static int stringSearch(String phrase, String searchFor)
{
   for (int i=0; i<phrase.length(); i++) 
   {
       if (phrase.substring(i,i+searchFor.length()).equals(searchFor))
           return i;
   }
   return -1;
}
II. 
public static int stringSearch (String phrase, String searchFor)
{
    int searchLen = searchFor.length();
    for (int i=0; i<phrase.length(); i+=searchLen)
    {
        if (i+searchLen <= phrase.length() && phrase.substring(i,i+searchLen).equals(searchFor))
            return i;
    }
    return -1;
}
III.
public static int stringSearch(String phrase, String searchFor)
{
    return phrase.indexOf(searchFor);
}
A

I only.

B

I and II only.

C

I and III only.

D

II and III only.

E

I, II, and III.