C语言字符串元素替换:将指定单词替换为星号的实现问题
搞定C语言字符串指定单词替换为星号的方案
你已经写好了lengthString和replace这两个基础工具函数,思路很清晰!接下来咱们把核心的redact函数补全,实现精准替换指定单词为等长星号的功能,完全满足你给出的示例需求。
需求回顾
输入字符串:
A big giant person scared me
需要替换的单词:giant、scared
预期输出:A big ***** person ****** me
完整可运行代码
#include <stdio.h> #include <string.h> // 自定义字符串长度计算函数 int lengthString(char* str) { int i = 0; while (str[i] != '\0') i++; return i; } // 将指定起始位置的length个字符替换为ch void replace(char* start, int length, char ch) { for (int i = 0; i < length; i++) start[i] = ch; } // 核心替换函数:遍历字符串,匹配字典中的单词并替换为星号 void redact(char* toRedact, char** dictionary, int dicSize) { char* current = toRedact; int strTotalLen = lengthString(toRedact); while (*current != '\0') { // 跳过单词前的所有空格,定位到单词起始 while (*current == ' ' && current < toRedact + strTotalLen) { current++; } if (*current == '\0') break; // 到字符串结尾就退出 // 找到当前单词的结束位置(空格或字符串末尾) char* wordEnd = current; while (*wordEnd != ' ' && *wordEnd != '\0') { wordEnd++; } int currentWordLen = wordEnd - current; // 遍历字典,检查当前单词是否需要替换 for (int i = 0; i < dicSize; i++) { int dictWordLen = lengthString(dictionary[i]); // 先判断长度是否一致,再逐字符匹配(避免部分匹配) if (currentWordLen == dictWordLen && strncmp(current, dictionary[i], currentWordLen) == 0) { replace(current, currentWordLen, '*'); break; // 匹配到一个目标单词就停止当前字典遍历 } } // 移动指针到下一个单词的起始位置 current = wordEnd; } } // 测试用例 int main() { // 注意:必须用字符数组存储字符串,不能用char* str = "..."(字符串常量不可修改) char inputStr[] = "A big giant person scared me"; char* redactDict[] = {"giant", "scared"}; int dictSize = sizeof(redactDict) / sizeof(redactDict[0]); redact(inputStr, redactDict, dictSize); printf("替换结果:%s\n", inputStr); return 0; }
关键细节说明
- 字符串可修改性:主函数里用
char inputStr[] = "..."而不是char* inputStr = "...",后者是只读的字符串常量,强行修改会触发未定义行为,这是C语言字符串处理的常见坑点。 - 完整单词匹配:通过定位单词的首尾边界(空格或字符串首尾),再对比长度+逐字符匹配,避免了部分匹配的问题(比如不会把
giantess里的giant误替换)。 - 工具函数复用:你写的
replace函数完美适配需求,直接用来把匹配到的单词替换成等长星号,非常高效。
运行这段代码,就能得到你想要的输出结果啦!
内容的提问来源于stack exchange,提问作者YasinYA
相关产品推荐
相关产品推荐

