【发布时间】:2012-01-19 10:37:25
【问题描述】:
编写一个名为 wordCount 的方法,该方法接受一个字符串作为其参数并返回字符串中的单词数。单词是一个或多个非空格字符的序列(' ' 以外的任何字符)。例如,调用 wordCount("hello") 应该返回 1,调用 wordCount("你好吗?") 应该返回 3,调用 wordCount("this string has wide spaces") 应该返回 5,调用 wordCount (" ") 应该返回 0。
我做了一个函数:
public static int wordCount(String s){
int counter = 0;
for(int i=0; i<=s.length()-1; i++) {
if(Character.isLetter(s.charAt(i))){
counter++;
for(i<=s.length()-1; i++){
if(s.charAt(i)==' '){
counter++;
}
}
}
}
return counter;
}
但我知道这有 1 个限制,它还会在字符串中的所有单词完成后计算空格数,并且它还会将 2 个空格算作可能是 2 个单词 :( 是否有预定义的字数统计功能?或者这个代码可以更正吗?
【问题讨论】:
-
你不能只做
String#split("\\s");并获取结果数组的长度。 -
您是否缺少
[homework]标签?
标签: java