我想知道如何编写一个方法来计算每个单词字母的单词数和数量 例如,如果输入是“蓝天”,作为回报,我采取的东西,告诉我有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;
}
我非常感谢能得到的任何帮助!谢谢!
答案 0 :(得分:7)
第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
答案 1 :(得分:1)
看看http://www.tutorialspoint.com/java/java_string_split.htm。 您应该能够使用Java String.split()函数以空格“”分隔字符串。 这应该给你一个包含每个单词的数组。然后它只是找到每个单词的长度。
答案 2 :(得分:0)
计算可能有帮助的词语
public static int countWords(String str)
{
int count = 1;
for (int i=0;i<=str.length()-1;i++)
{
if (str.charAt(i) == ' ' && str.charAt(i+1)!=' ')
{
count++;
}
}
return count;
}
public static void main(String[] args)
{
Scanner in = new Scanner(System.in);
System.out.print("Enter a sentence: ");
String sentence = in.nextline();
System.out.print("Your sentence has " + countWords(sentence) + " words.");
}
答案 3 :(得分:0)
这是我的代码 -
public void countWordsLetters(String s){
String str[]=s.split(" ");
System.out.println("No. of words in string::"+str.length);
for (int i=0;i<str.length;i++){
System.out.println("No of letters in "+i+" word "+str[i].length());
}
}
答案 4 :(得分:0)
Buddy,上面的大部分答案都是正确的,但是在计算String中的字符时没有人考虑过空格。希望你也能包含它。
for(int j=0;j<name.length();j++){ //here is name is my string
if(Character.isWhitespace(name.charAt(j))){
}else{
count+=1;
}
}
System.out.println("The word count is "+count);
答案 5 :(得分:0)
这是我的回答,这要感谢Sahil Nagpal的启发:
package exercise;
导入java.util.Scanner;
公共类method_letter {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.println("enter any string");
String s=in.nextLine();
System.out.println("the letter count :"+lettercount(s));
}
public static int lettercount (String s) {
int count=0;
for (int i=0; i<s.length(); i++) {
if(Character.isWhitespace(s.charAt(i))){
}else {
count+=1;
}
}
return count;
}
}