一尘不染

用字符串方法计算单词数?

java

我想知道如何编写一种仅通过使用charAt,length或substring之类的字符串方法来计算Java字符串中单词数的方法。

循环和if语句还可以!

我非常感谢我能获得的任何帮助!谢谢!


阅读 255

收藏
2020-09-08

共1个答案

一尘不染

public static int countWords(String s){

    int wordCount = 0;

    boolean word = false;
    int endOfLine = s.length() - 1;

    for (int i = 0; i < s.length(); i++) {
        // if the char is a letter, word = true.
        if (Character.isLetter(s.charAt(i)) && i != endOfLine) {
            word = true;
            // if char isn't a letter and there have been letters before,
            // counter goes up.
        } else if (!Character.isLetter(s.charAt(i)) && word) {
            wordCount++;
            word = false;
            // last word of String; if it doesn't end with a non letter, it
            // wouldn't count without this.
        } else if (Character.isLetter(s.charAt(i)) && i == endOfLine) {
            wordCount++;
        }
    }
    return wordCount;
}
2020-09-08