0

有人可以告诉我这有什么问题吗?我试图让程序返回字符串中的单词数。它陷入了无限循环......

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;

}
4

4 回答 4

3

两个问题。您没有在循环中重置 posBlank 的值,如果您传入一个没有空格的字符串,您的子字符串总是只返回整个字符串。你需要解决这两个问题。试试这个:

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;
}
于 2012-10-26T13:58:22.193 回答
2

wholeName.trim().split(" ").length改为使用

于 2012-10-26T13:59:14.283 回答
2

为什么不直接使用呢String.split(\\s)??

 String testname=wholename;
 String[] words = testname.split("\\s");
 sysout(words.length);
于 2012-10-26T14:02:29.970 回答
1
return wholename.length() - wholename.replace(" ", "").length() + 1
于 2012-10-26T14:05:45.783 回答