我想知道如何编写一种方法来计算单词数和每个单词字母的数量,例如,如果输入的是“ The Blue Sky”作为回报,我会得到一些东西,告诉我有3个单词3个字母4个字母3个字母
我已经找到了此代码
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;
}
我非常感谢我能获得的任何帮助!谢谢!
步骤1-使用空格分隔符查找句子中的单词数。
String CurrentString = "How Are You";
String[] separated = CurrentString.split(" ");
String sResultString="";
int iWordCount = separated.length;
sResultString = iWordCount +" words";
第2步-查找每个单词中的字母数。
for(int i=0;i<separated.length;i++)
{
String s = separated[i];
sResultString = sResultString + s.length + " letters ";
}
// Print sResultString
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句