Question:
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
Solution:
JAVAclass Solution {
public int countSegments(String s) {
String trimmed = s.trim();
if (trimmed.equals("")) {
return 0;
}
return trimmed.split("\\s+").length;
}
}
已有0条评论
还没有任何评论,你来说两句吧!