Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

Assuming that s and t are Strings, which of the following code fragments are suc

ID: 672842 • Letter: A

Question

Assuming that s and t are Strings, which of the following code fragments are such that the value returned by s.indexOf( t ) before the code is executed is equal to the value of the int n after the code is executed?

I.

int n = -1;
    int tSize = t.length();
    boolean found = false;
    while ( !found && tSize <= s.length() )
    {
      n++;
      if ( t.equals( s.substring( 0, tSize ) ) )
        found = true;
      else
        s = s.substring( 1 );
    }
    if ( !found )
      n = -1;     

II.

    int n = -1;
    int sSize = s.length();
    int tSize = t.length();
    boolean found = false;
    while ( !found && n + tSize + 1 <= sSize )
    {
      n++;
      if ( t.equals( s.substring( n, n + tSize ) ) )
        found = true;
    }
    if ( !found )
      n = -1;     

III.

  int n = 0;
    int sSize = s.length();
    int tSize = t.length();
    boolean found = false;
    while ( !found && n + tSize <= sSize )
    {
      if ( t.equals( s.substring( n, n + tSize ) ) )
        found = true;

      n++;
    }
    if ( found )
      n--;
    else
      n = -1;

A. I only

B. II only

C. III only

D. I and II only

E. I, II, and III

I.

int n = -1;
    int tSize = t.length();
    boolean found = false;
    while ( !found && tSize <= s.length() )
    {
      n++;
      if ( t.equals( s.substring( 0, tSize ) ) )
        found = true;
      else
        s = s.substring( 1 );
    }
    if ( !found )
      n = -1;     

II.

    int n = -1;
    int sSize = s.length();
    int tSize = t.length();
    boolean found = false;
    while ( !found && n + tSize + 1 <= sSize )
    {
      n++;
      if ( t.equals( s.substring( n, n + tSize ) ) )
        found = true;
    }
    if ( !found )
      n = -1;     

III.

  int n = 0;
    int sSize = s.length();
    int tSize = t.length();
    boolean found = false;
    while ( !found && n + tSize <= sSize )
    {
      if ( t.equals( s.substring( n, n + tSize ) ) )
        found = true;

      n++;
    }
    if ( found )
      n--;
    else
      n = -1;

Explanation / Answer

D. I and II only

in option III, after matching the substirng of s with t , value of n is increase by 1 so that III option was wrong.