在字符串方法中计算单词?

2022-09-01 07:02:59

我想知道如何编写一种方法来仅使用charAt,length或子字符串等字符串方法来计算java字符串中的单词数。

循环和 if 语句是可以的!

我真的很感激我能得到的任何帮助!谢谢!


答案 1

即使有多个空格以及前导空格和/或尾随空格以及空行,这也有效:

String trim = s.trim();
if (trim.isEmpty())
    return 0;
return trim.split("\\s+").length; // separate string around spaces

希望有所帮助。有关拆分的详细信息,请单击此处。


答案 2
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;
}