ami*_*lou 3 java string int android cpu-word
我想知道如何编写一个方法来计算单词的数量和每个单词字母的数量,例如,如果输入是"蓝天"作为回报我带一些东西,告诉我有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;
}
Run Code Online (Sandbox Code Playgroud)
我真的很感激我能得到的任何帮助!谢谢!
第1步 - 使用空格分隔符查找句子中的单词数.
String CurrentString = "How Are You";
String[] separated = CurrentString.split(" ");
String sResultString="";
int iWordCount = separated.length;
sResultString = iWordCount +" words";
Run Code Online (Sandbox Code Playgroud)
第2步 - 在每个单词中查找字母数.
for(int i=0;i<separated.length;i++)
{
String s = separated[i];
sResultString = sResultString + s.length + " letters ";
}
// Print sResultString
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
12604 次 |
| 最近记录: |