- 输入带空格的字符串,求单词个数
- __ueooe_eui_sjje__ ---->3
- syue__jdjd____die_ ---->3
- shuue__dju__kk ---->3
-
#include <stdio.h> #include <string.h> // 自定义函数来判断字符是否为空白字符 int isSpace(char c) { return c == ' ' || c == '\t' || c == '\n' || c == '\r'; } // 计算字符串中单词的数量 int countWords(const char* str) { int state = 0; // 0: 在单词外, 1: 在单词内 int wordCount = 0; while (*str) { // 如果当前字符不是空白字符并且状态是“在单词外” if (!isSpace(*str) && state == 0) { state = 1; // 进入单词 wordCount++; // 增加单词计数 } // 如果当前字符是空白字符并且状态是“在单词内” else if (isSpace(*str) && state == 1) { state = 0; // 离开单词 } str++; } return wordCount; } int main() { char a1[]=" ueooe eui sjje "; char a2[]="syue jdjd die "; char a3[]="shuue dju kk"; size_t len1 = strlen(a1); size_t len2 = strlen(a2); size_t len3 = strlen(a3); // 计算单词个数 int wordCount1 = countWords(a1); int wordCount2 = countWords(a2); int wordCount3 = countWords(a3); // 输出结果 printf("a1单词个数是: %d\n", wordCount1); printf("a2单词个数是: %d\n", wordCount2); printf("a3单词个数是: %d\n", wordCount3); return 0; }