user1721929
user1721929

Reputation: 33

Number of words in a string Infinite Loop

Can someone tell me what is wrong with this? I'm trying to get the program to return the number of words in the string. It is stuck in an infinite loop...

int NumberNames(String wholename)

{    
    String testname=wholename;

    int numnames=0;

     int posBlank= testname.indexOf(' ');

     while(testname.length()>0)
    {   
       testname = testname.trim();

       testname=testname.substring(posBlank+1,testname.length());

       numnames++;

       System.out.println(testname);
    }    

    return numnames;

}

Upvotes: 0

Views: 156

Answers (4)

David M
David M

Reputation: 72850

Two issues. You're not resetting the value of posBlank within your loop, and if you pass in a string without spaces, your substring always just returns the whole string. You'll need to solve both. Try this:

int NumberNames(String wholename)
{
    String testname=wholename;
    int numnames=1;
    int posBlank= testname.indexOf(' ');

    while(posBlank > 0)
    {   
       testname = testname.trim();
       testname=testname.substring(posBlank+1,testname.length());
       posBlank= testname.indexOf(' ');
       numnames++;
       System.out.println(testname);
    }    

    return numnames;
}

Upvotes: 3

LJ2
LJ2

Reputation: 613

return wholename.length() - wholename.replace(" ", "").length() + 1

Upvotes: 1

PermGenError
PermGenError

Reputation: 46398

why not just use String.split(\\s) instead??

 String testname=wholename;
 String[] words = testname.split("\\s");
 sysout(words.length);

Upvotes: 2

gefei
gefei

Reputation: 19766

use wholeName.trim().split(" ").length instead

Upvotes: 2

Related Questions