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

Phi*_*tty 26 java string methods count

我想知道如何只使用charAt,length或substring等字符串方法编写一个方法来计算java字符串中的单词数.

循环和if语句都可以!

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

Cor*_* G. 69

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

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

希望有所帮助.有关拆分的更多信息.

  • 我会在这里使用\\ W而不是\\ s,因为你可以拥有除空格之外的其他东西. (7认同)
  • 简短,甜蜜,有效。 (2认同)

koo*_*ool 24

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;
}
Run Code Online (Sandbox Code Playgroud)

  • 您需要考虑撇号和引号以及其他特殊字符。 (2认同)
  • 您在注释中使用了缩写(“不是”、“不会”、“不会”),但您的代码无法处理它们。它也不会处理打击犯罪的犬类。 (2认同)

fre*_* Ha 11

嗨,我刚刚想到了StringTokenizer,就像这样:

String words = "word word2 word3 word4";
StringTokenizer st = new Tokenizer(words);
st.countTokens();
Run Code Online (Sandbox Code Playgroud)

  • 这有效,但它不是 String 方法,它使用单独的 StringTokenizer 类。问题是如何在不使用其他类的情况下做到这一点。 (2认同)

Ram*_*gai 7

简单地用,

str.split("\\w+").length ;
Run Code Online (Sandbox Code Playgroud)