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;
}