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
题目含义:计算字符串中的非空子串的个数。
思路:找到每个单词的开头字母,就算作一个单词
1 public int countSegments(String s) { 2 int res=0; 3 for(int i=0; i<s.length(); i++) 4 if(s.charAt(i)!=' ' && (i==0 || s.charAt(i-1)==' ')) 5 res++; 6 return res; 7 }