【发布时间】:2014-09-17 17:11:24
【问题描述】:
//统计String中的单词总数
class Word
{
static int Wordcount(String k)
{
int count=0;
char ch[]=k.toCharArray();
for(int i=0;i<k.length();i++)
{
if(ch[i]==32 && ch[i+1]!=32)
{
count++;
}
}
return(++count);
}
public static void main(String... s)
{
String k="java is a programming lan";
/* if input string is "java is a prog lan " then its gives//Exception
*/
int b=Wordcount(k);
System.out.println("Your input String has "+b +" words");
}
}
// 异常aati h agr string khtm ho ri h space se
【问题讨论】:
-
为什么不用String.split()方法来获取字数呢?
-
说
ch[i] == 32非常令人困惑。您将char与int进行比较,而不是像他们记忆的ASCII 表中的每个人一样。请改用ch[i] == ' '。
标签: java string indexoutofboundsexception