在字符串方法中计算单词? [英] Count words in a string method?
本文介绍了在字符串方法中计算单词?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想知道如何编写一个方法来仅使用 charAt、length 或 substring 等字符串方法来计算 java 字符串中的单词数.
I was wondering how I would write a method to count the number of words in a java string only by using string methods like charAt, length, or substring.
循环和 if 语句没问题!
Loops and if statements are okay!
我非常感谢我能得到的任何帮助!谢谢!
I really appreciate any help I can get! Thanks!
推荐答案
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;
}
这篇关于在字符串方法中计算单词?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文