Count the number of segments in a string, where a segment is defined to be a contiguous sequence of non-space characters.
Please note that the string does not contain any non-printable characters.
Example:
Input: "Hello, my name is John"
Output: 5
计算字符串中的段数,其中段被定义为非空格字符的连续序列。
请注意,字符串不包含任何不可打印的字符。
例:
输入: “Hello, my name is John” 输出: 5
思路:
用split方法分割字符串,接着循环判断字符串数组元素是否为空。注意判断时控制不能用 “” 或者null来判断,要用isEmpty()方法。
public int countSegments(String s) {
String[] sa = s.split(" ");
int result = 0;
for(int i=0 ; i<sa.length ; i++){
if( !sa[i].isEmpty() ) {
result++;
}
}
return result;
}