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)
希望有所帮助.有关拆分的更多信息.
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)
fre*_* Ha 11
嗨,我刚刚想到了StringTokenizer,就像这样:
String words = "word word2 word3 word4";
StringTokenizer st = new Tokenizer(words);
st.countTokens();
Run Code Online (Sandbox Code Playgroud)