编写程序,输入一个字符串(该字符串由一个或多个空格分隔的单词构成),完成以下功能: 1. 判断该字符串中是否含有大写字母,如有输出“Yes”,否则输出“No”提示; 2. 请将字符串中每个单词的首字母变成大写字母后并输出该字符串。
时间: 2025-01-22 14:17:01 浏览: 39
要完成这个任务,你可以使用C语言中的标准库函数。首先,你需要从用户那里获取输入的字符串,然后遍历字符串判断是否包含大写字母,接着分割字符串并处理每个单词的首字母。以下是完整的示例代码:
```c
#include <stdio.h>
#include <ctype.h> // 使用ctype_h库来检查字符类型
#include <string.h> // 使用strlen和strtok函数
// 分割字符串并返回首字母大写的单词数组
char** split_and_capitalize(char *input) {
char *token, *delim = " ";
char **words = NULL;
int count = 0;
token = strtok(input, delim);
while (token != NULL) {
words = realloc(words, sizeof(char*) * (count + 1)); // 动态分配内存
if (words == NULL) {
fprintf(stderr, "Memory allocation failed.\n");
exit(1);
}
words[count] = strdup(token); // 深拷贝单词防止破坏原始字符串
if (!isupper(*words[count])) { // 如果不是首字母大写
words[count][0] = toupper(words[count][0]); // 转换为大写
}
count++;
token = strtok(NULL, delim);
}
words = realloc(words, sizeof(char*) * count); // 减少多余的空间
return words;
}
int main() {
char input[100];
printf("Enter a string with space-separated words: ");
fgets(input, sizeof(input), stdin);
// 移除行尾的换行符
input[strcspn(input, "\n")] = '\0';
char **words = split_and_capitalize(input);
for (int i = 0; words[i]; i++) {
printf("%s ", words[i]);
}
// 输出是否有大写字母
int has_upper = any_uppercase(words, count);
free(words[0]);
for (int i = 1; i < count; i++) {
free(words[i]);
}
free(words);
if (has_upper) {
printf("\nYes\n");
} else {
printf("\nNo\n");
}
return 0;
}
// 辅助函数,检查数组中是否有大写字母
int any_uppercase(char **array, int size) {
for (int i = 0; i < size; i++) {
if (isupper(array[i][0])) {
return 1;
}
}
return 0;
}
```
这段代码定义了一个`split_and_capitalize`函数用于分割字符串并处理每个单词的首字母,`main`函数则负责接收用户的输入、调用这两个函数,并根据结果输出相应的提示。
阅读全文
相关推荐

















