c语言写从键盘输入一个包含多个单词的字符 串,将每个单词从字符串中分离出来保存,并且单词首宇母大写。
时间: 2024-05-02 21:23:56 浏览: 21
可以使用C语言中的字符串处理函数strtok()和toupper()来实现此功能。具体实现步骤如下:
1. 定义一个字符数组存储输入的字符串,使用scanf()函数从键盘读入。
2. 使用strtok()函数将字符串分割成单词,并将单词存储到另一个字符数组中。
3. 对每个单词进行处理,将首字母转换为大写字母,可以使用toupper()函数。
4. 输出处理后的结果。
示例代码如下:
```
#include <stdio.h>
#include <string.h>
#include <ctype.h>
int main() {
char str[100];
char words[20][20];
int i = 0, j = 0;
printf("请输入一个包含多个单词的字符串:");
scanf("%[^\n]", str); // 读取包含空格的字符串
char *token = strtok(str, " "); // 分割字符串
while (token != NULL) {
strcpy(words[i], token); // 存储单词
token = strtok(NULL, " ");
i++;
}
printf("分离出的单词为:\n");
for (j = 0; j < i; j++) {
words[j][0] = toupper(words[j][0]); // 将首字母转换为大写字母
printf("%s\n", words[j]); // 输出单词
}
return 0;
}
```
注意:本代码仅对输入的字符串进行了简单的处理,没有考虑特殊情况,例如字符串中包含标点符号等。在实际应用中需要根据需求进行修改。