统计字符串中的单词个数,这里的单词指的是连续的不是空格的字符。
请注意,你可以假定字符串里不包括任何不可打印的字符。
示例:
输入: "Hello, my name is John"
输出: 5
public class test0225 {
public static void main(String[] args) {
Solution S = new Solution();
String s = "Hello, my name is John";
int a = S.countSegments(s);
System.out.println(a);
}
}
class Solution {
public int countSegments(String s) {
int count = 0;
char[] chars = s.toCharArray();
if(chars.length==0) //判断字符串是否为空
return 0;
if(chars[0]!=' ') //判断首位是否为字符
count ++;
for(int i =1;i<chars.length-1;i++)
{
if(chars[i]==' '&&chars[i+1]!=' ')
//如果第i位为空格,i+1位不是空格,那就记一个单词数
{
count ++;
}
}
return count ;
}
}
本文介绍了一个Java程序,用于统计字符串中单词的数量。该程序通过遍历字符串中的字符,利用空格来判断单词的边界,从而准确地计算出单词总数。
472

被折叠的 条评论
为什么被折叠?



