1243. 字符串中的单词数
计算字符串中的单词数,其中一个单词定义为不含空格的连续字符串。
样例
Example:
Input: "Hello, my name is John"
Output: 5
Explanation:There are five string "Hello"、"my"、"name"、"is"、"John"
注意事项
字符串中不包含任何 无法打印 的字符.
public class Solution {
/**
* @param s: a string
* @return: the number of segments in a string
*/
public int countSegments(String s) {
// write yout code here
int n = 0;
for(int i = 0; i < s.length(); i++){
if(i==0&&s.charAt(i)!=' '||i>0&&s.charAt(i)!=' '&&s.charAt(i-1)==' ')
n++;
}
return n;
}
}