字符串无限循环中的字数

时间:2012-10-26 13:56:34

标签: java

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

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 个答案:

答案 0 :(得分: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;
}

答案 1 :(得分:2)

使用wholeName.trim().split(" ").length代替

答案 2 :(得分:2)

为什么不使用String.split(\\s)代替?

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

答案 3 :(得分:1)

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