LeetCode刷题实战434:字符串中的单词数
You are given a string s, return the number of segments in the string. A segment is defined to be a contiguous sequence of non-space characters.
示例
输入: "Hello, my name is John"
输出: 5
解释: 这里的单词是指连续的不是空格的字符,所以 "Hello," 算作 1 个单词。
解题
class Solution {
public int countSegments(String s) {
String[] ss = s.split(" ");
int count = 0;
/**
* 这里有一个坑,就是”“会分割出空的字符串,我们需要对空字符串进行判空
*/
for (String s1:ss){
if (!s1.equals("")){
count++;
}
}
return count;
}
}
评论
