计算字符串中的单词数,其中一个单词定义为不含空格的连续字符串。
样例
样例:
输入: "Hello, my name is John"
输出: 5
注意事项
字符串中不包含任何 无法打印 的字符.
解题思路:
使用空格分割即可。注意过滤掉多余的空格。
public class Solution {
/**
* @param s: a string
* @return: the number of segments in a string
*/
public int countSegments(String s) {
// write yout code here
String[] ss = s.split(" ");
int res = 0;
for(int i=0; i<ss.length; i++){
if(ss[i].equals("") || ss[i].equals(" "))
continue;
res++;
}
return res;
}
}
本文介绍了一种计算不含空格的连续字符串中单词数量的方法。通过使用空格作为分隔符,过滤多余空格,有效计算出字符串中的单词总数。
1702

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



