# 434. Number of Segments in a String 字符串中的单词数

@TOC

## # 题目描述

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
``````

## # 解题方法

### # 统计

``````public class Solution {
public int countSegments(String s) {
int count = 0;
for(int i = 0; i < s.length(); i++){
if(s.charAt(i) != ' ' && (i == 0 || s.charAt(i - 1) == ' ')){
count++;
}
}
return count;
}
}
``````

### # 正则表达式

``````public int countSegments(String s) {
String trimmed = s.trim();
if (trimmed.length() == 0) return 0;
else return trimmed.split("\\s+").length;
}
``````

python版本：

``````class Solution(object):
def countSegments(self, s):
"""
:type s: str
:rtype: int
"""
s = re.sub("\s+", " ", s)
s = s.strip()
if not s: return 0
return len(s.split(" "))
``````

``````class Solution(object):
def countSegments(self, s):
"""
:type s: str
:rtype: int
"""
return len(re.findall("\S+", s))
``````

### # 字符串分割

python的split()函数，默认的参数就是按照连续空格进行分割。注意，千万不要写参数为`" "`

``````class Solution(object):
def countSegments(self, s):
"""
:type s: str
:rtype: int
"""
return len(s.split())
``````

## # 日期

2017 年 5 月 ５ 日 2018 年 11 月 24 日 —— 周六快乐