C程序开发求助:如何将字符串中指定单词转为大写
问题:C程序中查找单词并仅将目标单词转为大写
我想编写一个C程序,实现以下功能:
- 查找给定字符串中某个单词(比如
good)的所有出现位置 - 将该单词的所有出现转为大写
示例输入:
输入字符串:good morning. have a good day.
示例输出:
The word 'good' was found at location 1
The word 'good' was found at location 22
GOOD morning. have a GOOD day.
我已经写了一段代码,但遇到了问题:当尝试用ctype.h的toupper函数时,整个文本都会被转为大写,而不是仅目标单词。以下是我的代码:
#include <stdio.h> #include <string.h> void main() { char str[1000], pat[20] = "good"; int i = 0, j, mal = 0, flag = 0; printf("Enter the string :"); gets(str); while (str[i] != '\0') { if (str[i] == pat[0]) { j = 1; //if next character of string and pat same while(pat[j] != '\0' && str[j + i] != '\0' && pat[j] == str[j + i]) { j++; flag = 1; } if (pat[j] == '\0') { mal += 1; printf("\n The word was found at location %d.\n" , i + 1); } } i++; if (flag == 0) { if (str[j + i] == '\0') printf(" The word was not found ") ; } } printf("The word was found a total of %d times", mal); }
恳请大家帮忙解决这个转大写的问题,谢谢!
解决方案
咱们先把原代码里的小问题理顺,再实现仅目标单词转大写的功能:
- 替换不安全的
gets函数:gets存在缓冲区溢出风险,换成fgets更安全,记得处理掉fgets读取的换行符。 - 修复匹配逻辑的小bug:原代码里的
flag变量逻辑有问题,会导致错误的未找到提示,咱们换更直接的匹配判断方式。 - 精准转换目标单词:找到匹配的单词位置后,只遍历该单词的每个字符调用
toupper,这样就不会影响字符串里的其他内容了。
修改后的完整代码如下:
#include <stdio.h> #include <string.h> #include <ctype.h> // 引入ctype.h来使用toupper函数 int main() { // 标准C中main函数建议返回int类型 char str[1000], pat[20] = "good"; int i = 0, j, count = 0; int pat_len = strlen(pat); // 预先计算目标单词的长度,避免重复计算 printf("Enter the string: "); fgets(str, sizeof(str), stdin); // 移除fgets读取到的换行符 str[strcspn(str, "\n")] = '\0'; while (str[i] != '\0') { // 直接用strncmp判断当前位置是否匹配整个目标单词 if (strncmp(&str[i], pat, pat_len) == 0) { count++; printf("The word '%s' was found at location %d\n", pat, i + 1); // 仅将匹配到的单词转为大写 for (j = 0; j < pat_len; j++) { str[i + j] = toupper(str[i + j]); } // 跳过已处理的单词长度,避免重复匹配同一单词 i += pat_len; continue; } i++; } if (count == 0) { printf("The word '%s' was not found\n", pat); } else { printf("\nResult string:\n%s\n", str); printf("The word '%s' was found a total of %d times\n", pat, count); } return 0; }
额外优化(可选):整词匹配
如果需要确保匹配的是独立单词(比如不会把goodbye里的good当成有效匹配),可以添加前后字符的判断逻辑:
// 检查是否是单词开头:要么是字符串起始,要么前一个字符不是字母 int is_word_start = (i == 0) || !isalpha(str[i-1]); // 检查是否是单词结尾:要么是字符串结束,要么后一个字符不是字母 int is_word_end = (str[i + pat_len] == '\0') || !isalpha(str[i + pat_len]); if (is_word_start && is_word_end && strncmp(&str[i], pat, pat_len) == 0) { // 执行匹配后的逻辑 }
测试你的示例输入:
输入字符串:good morning. have a good day.
输出结果:
The word 'good' was found at location 1
The word 'good' was found at location 22Result string:
GOOD morning. have a GOOD day.
The word 'good' was found a total of 2 times
这样就完美实现你的需求啦!
内容的提问来源于stack exchange,提问作者DAVID
相关产品推荐
相关产品推荐

