统计字符串中的单词个数,这里的单词指的是连续的不是空格的字符。
请注意,你可以假定字符串里不包括任何不可打印的字符。
示例:
输入: "Hello, my name is John" 输出: 5 解释: 这里的单词是指连续的不是空格的字符,所以 "Hello," 算作 1 个单词。
代码:
int countSegments(char* s) { // LeeCode 434. 字符串中的单词数
if (s == NULL)
return 0;
int len = strlen(s);
if (len < 1)
return 0;
int count = 0;
for (int i = 0; i < len; i++) {
if (s[i] != ' ') {
if (i == len - 1) {
count++;
}
else if (s[i+ 1] == ' ') {
count++;
}
}
}
return count;
}
测试代码:
void testLeeCode434() {
const char* s = "Hello, my name is John";
char str[50];
strcpy_s(str, sizeof(str), s);
printf("str: %s, countSegments: %d \n", str, countSegments(str));
}
打印:
ok。测试代码中本来是想用strcpy函数拷贝字符串的,但是提示函数不安全,用strcpy_s函数拷贝。后缀为_s的函数应该都是安全函数。