number of segments in a string


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:

1
2
Input: "Hello, my name is John"
Output: 5

Solution

1
2
3
4
5
6
7
8
9
10
11
12
class {
public int countSegments(String s) {
String[] str = s.trim().split(" ");
int re = str.length;
for(int i=0; i<str.length; i++) {
if("".equals(str[i])) {
re--;
}
}
return re;
}
}