酷代码 AI
菜单

题目描述 输入一行只包含空格和字母的字符,统计出其中单词的个数 单词: 不包含空格的连续的字符串就是一个单词 输入 一行字符串,总长度不超过1000。 输出 输出为1行,输出其中单词的个数

Python 实现 ```python # 读取输入的字符串 input_str = input() # 去除字符串首尾的空格 input_str = input_str.strip() if input_str == "": print(0) else: # 按空格分割字符串 words = input_str.split() # 输出单词的个数 print(len(words)) ``` 代码解释: 1. 输入读取:使用`input()`函数读取用户输入的一行字符串。 2. 去除首尾空格:使用`strip()`方法去除字符串首尾的空格,避免因首尾空格影响单词个数的统计。 3. 空字符串判断:如果去除空格后字符串为空,说明没有单词,直接输出 0。 4. 分割字符串并统计单词个数:使用`split()`方法按空格分割字符串,得到一个单词列表`words`,然后使用`len()`函数计算列表的长度,即单词的个数。 C 语言实现 ```c #include <stdio.h> #include <string.h> #include <ctype.h> #define MAX_LEN 1000 int main() { char input_str[MAX_LEN + 1]; // 读取输入的字符串 fgets(input_str, sizeof(input_str), stdin); // 去除换行符 input_str[strcspn(input_str, "\n")] = 0; int len = strlen(input_str); int word_count = 0; int in_word = 0; for (int i = 0; i < len; i++) { if (isspace(input_str[i])) { in_word = 0; } else if (!in_word) { word_count++; in_word = 1; } } // 输出单词的个数 printf("%d\n", word_count); return 0; } ``` 代码解释: 1. 变量定义与输入读取: - 定义字符数组`input_str`用于存储输入的字符串,数组大小为`MAX_LEN + 1`,为字符串结尾的空字符`'\0'`留出空间。 - 使用`fgets()`函数读取用户输入的字符串。 2. 去除换行符:使用`strcspn()`函数找到换行符的位置,将其替换为`'\0'`,去除换行符。 3. 单词个数统计: - 使用`in_word`作为标志变量,用于标记当前是否在一个单词内。 - 遍历字符串,当遇到空格时,将`in_word`置为 0,表示不在单词内;当遇到非空格字符且`in_word`为 0 时,说明进入了一个新的单词,单词个数`word_count`加 1,并将`in_word`置为 1。 4. 输出结果:使用`printf()`函数输出单词的个数。 [2025-12-07 17:39:44 | AI问答 | 658点数解答]

服务商
相关提问
发财导航,免费问AI
实用工具查看更多