# C#LeetCode刷题之#434-字符串中的单词数​​​​​​​（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.

Input: “Hello, my name is John”

Output: 5

```public class Program {

public static void Main(string[] args) {
var s = "Hello, my name is Iori!";
var res = CountSegments(s);
Console.WriteLine(res);

s = "It's mine!";
res = CountSegments2(s);
Console.WriteLine(res);

s = "using System.Collections.Generic;";
res = CountSegments3(s);
Console.WriteLine(res);

s = "Hello, my daughter's name is Cherry!";
res = CountSegments4(s);
Console.WriteLine(res);

}

private static int CountSegments(string s) {
var split = s.Split(' ');
var index = 0;
foreach(var item in split) {
if(item.Trim() != "") index++;
}
return index;
}

private static int CountSegments2(string s) {
string[] split = s.Split(new char[] { ' ' },
StringSplitOptions.RemoveEmptyEntries);
return split.Length;
}

private static int CountSegments3(string s) {
var res = 0;
var notEmpty = false;
for(var i = 0; i < s.Length; i++) {
if(s[i] != ' ') notEmpty = true;
else {
if(notEmpty) {
res++;
notEmpty = false;
}
}
}
if(notEmpty) { res++; }
return res;
}

private static int CountSegments4(string s) {
var res = 0;
var preEmpty = true;
for(var i = 0; i < s.Length; i++) {
if(preEmpty && s[i] != ' ') res++;
preEmpty = s[i] == ' ';
}
return res;
}

}```

```5
2
2
6```