【发布时间】:2015-10-17 02:03:43
【问题描述】:
编写一个名为 wordCount 的方法,该方法接受一个字符串作为其参数并返回字符串中的单词数。单词是一个或多个非空格字符的序列(' ' 以外的任何字符)。例如,调用 wordCount("hello") 应该返回 1,调用 wordCount("你好吗?") 应该返回 3,调用 wordCount("this string has wide spaces") 应该返回 5,调用 wordCount (" ") 应该返回 0。
好的,所以我的问题是当程序输入的字符串/短语单词开始时 使用空格而不是单词,它不会在句子中注册以下单词并返回值 1。
所以如果 wordCount 是("这个字符串有很宽的空格") 应该返回 5,但只退出 0。我不明白你为什么能帮我理解我搞砸了?
这是我的方法:
public static int wordCount(String s) {
int word = 0;
if(s!=null)
if(s.charAt(0)!=' ') {
word++;
}
for(int i=0; i<=s.length(); i++)
{
if(s.charAt(i)!=' ' && s.charAt(i+1) ==' ')
{
word++;
}
return word;
}
return word;
}
【问题讨论】:
-
A
char不能与空的String进行比较,如错误所示。您是否打算检查字符是否为空格?s.charAt(0) != ' ' -
stackoverflow.com/questions/8102754/java-word-count-program google 第一击:“java word count”
-
@Andreas 是的,我希望它查看是否有空格并跳过它,这样只会计算单词而不包括空格。每当我将 "" 更改为 '' 时,我都会收到更多错误通知...
标签: java