Dream
Dream

Reputation: 3

Count Words Using indexOf

I can't use arrays, only simple Java (if, for, while, substring, length, indexOf)

public int howManyWords(String s){
        
    myString = "I have a dream";
    int count = 1;
    int length = 0;
    while(count>=0){
        
        count = myString.substring(String.valueOf(length),myString.indexOf(" "));
        count++;
        length = myString.indexOf(" ");
    
    }
    
     return count;
}

Should return 4

Upvotes: 0

Views: 654

Answers (3)

Nenad Jovicic
Nenad Jovicic

Reputation: 185

First of all, you made infinite loop, because count is 1, and you just increase it.

Second, you haven't even try to write this code in some IDE, because it would throw you a syntax error, because you are assigning string to int, when you do count = myString.substring()

So, instead of using count in loop, you can use myString.indexOf

something like this could work if you don't care what is going to happen with myString

int count = 0;

while(myString.indexOf(" ") >= 0) {
  count++;
  myString = myString.substring(myString.indexOf(" ") + 1)
}

return count;

Upvotes: 1

Swathi Mudda
Swathi Mudda

Reputation: 50

Edited : Added missing else case.

Try the following code :

Remove the counted words from your string using the substring and indexOf, and increment the count in each iteration.

public int countWords(String s){
        
    String myString = "I have a dream";
    int count = 0;
    int length = myString.length();
    while(length>0){
        if((myString.indexOf(" ")!=-1) && (myString.indexOf(" ")+1)<length){
            myString = myString.subString(myString.indexOf(" ")+1);
            count++;
            length = myString.length();
        }
        else {
            length = 0;
            break;
        }
    
    }
    
     return count;
}

PS: Conventionally, your method names should denote actions, hence I suggested it to be countWords instead of howManyWords.

Upvotes: 0

Abra
Abra

Reputation: 20914

Let's assume that the string you are testing does not contain leading or trailing spaces, because that affects the solution. The example string in your question does not contain leading or trailing spaces.

Simply call method indexOf(String, int) in a loop and in each iteration you set the int parameter to one more than what you got in the previous iteration. Once the value returned by method indexOf() is -1 (minus one), you are done. But don't forget to add the last word after you exit the loop.

String myString = "I have a dream";
int count = 0;
int index = 0;
while (index >= 0  &&  index < myString.length()) {
    index = myString.indexOf(" ", index);
    System.out.println("index = " + index);
    if (index >= 0) {
        index++;
        count++;
    }
}
if (index < 0) {
    count++;
}
System.out.println("count = " + count);

Upvotes: 0

Related Questions