?

AP® Computer Science A

Free Version

Upgrade subject to access all content

Difficult

Count Characters in String Until Descending Character

APCSA-1BEGTY

Given that variable str is a string with a length of at least 1, which of the following code segments would count the number of characters from the beginning of str until it first encounters a character that is in descending sequence?

Examples:

1) If str equals "alluring", then the variable count would equal 4 since the fifth letter "r" is less than the fourth letter "u".

2) If str equals "zone", then the variable count would equal 1 since the second letter "o" is less than the first letter "z".

I.

    String str = // assume that str is assigned a string with length >=1
    int i=0, count=1;

    while (str.substring(i,i+1).compareTo(str.substring(i+1,i+2)) <=0 && i<str.length()-1)
    {
        count++;
        i++;
    }

II.

    String str = // assume that str is assigned a string with length >=1
    int i=0, count=1;

    while (i<str.length()-1 && str.substring(i,i+1).compareTo(str.substring(i+1,i+2))<=0)
    {
         count++;
         i++;
    }

III.

    String str = // assume that str is assigned a string with length >=1
    int i=0, count=1;

    while (i<str.length() && str.substring(i+1,i+2).compareTo(str.substring(i,i+1))>0)
    {
        count++;
        i++;
    }
A

I only

B

II only

C

III only

D

I and II only

E

II and III only