C语言如何仅删除字符串中完整单词the/The而非单个匹配字符
完整单词删除功能修复方案
原代码问题说明
你的代码核心逻辑错误:当前嵌套循环是逐个匹配单个字符,只要输入字符和the中的任意字符重合就直接删除,没有做连续完整单词的匹配校验,也没有判断单词边界,自然会误删Theatre这类包含t/h/e字符的其他单词。
实现要求
要仅删除完整的the/The单词,必须同时满足两个判断条件:
- 从当前位置开始的连续3个字符,不区分大小写匹配
the - 这3个字符是独立单词:前后要么是空格,要么是字符串的开头/结尾
修改后可运行代码
#include <stdio.h> #include <string.h> #include <strings.h> #define SIZE 100 void func(); int main() { func(); return 0; } void func() { int i, inputlen, removelen = 3; char input[SIZE]; printf("Enter the string: \n"); // 替换不安全的gets函数为fgets fgets(input, SIZE, stdin); // 移除fgets读取的末尾换行符 inputlen = strlen(input); if (input[inputlen - 1] == '\n') { input[inputlen - 1] = '\0'; inputlen--; } for (i = 0; i <= inputlen - removelen; ) { // 不区分大小写匹配连续3个字符 if (strncasecmp(input + i, "the", removelen) == 0) { // 校验单词边界 int isWordStart = (i == 0) || (input[i-1] == ' '); int isWordEnd = (i + removelen == inputlen) || (input[i + removelen] == ' '); if (isWordStart && isWordEnd) { // 匹配到目标单词,将后续内容前移3位完成删除 memmove(input + i, input + i + removelen, inputlen - i - removelen + 1); inputlen -= removelen; // 删除后当前位置需要重新校验,不递增i continue; } } // 未匹配到目标,指针后移 i++; } // 清理删除开头单词后残留的前导空格 char *output = input; while (*output == ' ') output++; printf("%s\n", output); }
测试效果
输入示例:The Dhillon Theatre is now Fun Republic
输出结果:Dhillon Theatre is now Fun Republic
不会误删Theatre中的T、h、e字符,符合需求。
内容的提问来源于stack exchange,提问作者Aliterminate Joham
相关产品推荐
相关产品推荐

