我正在尝试替换 C 字符数组中的整个单词并跳过子字符串。我进行了研究,最终得出了非常艰难的决定,同时我认为如果有人可以帮助我,我会有更好的想法。 假设我有字符串:
char sentence[100]= "apple tree house";
我想用数字 12 替换树:
"apple 12 house"
我知道单词是由空格分隔的,所以我的想法是:
1.用分隔符空格对字符串进行标记
2.在 while 循环中使用库函数 STRCMP 检查字符串是否等于标记,以及是否要进行替换。
当我尝试替换字符串时,问题就出现了,因为我无法做到。
void wordreplace(char string[], char search[], char replace[]) {
// Tokenize
char * token = strtok(string, " ");
while (token != NULL) {
if (strcmp(search, token) == 0) {
REPLACE SEARCH STRING WITH REPLACE STRING
}
token = strtok(NULL, " ");
}
printf("Sentence : %s", string);
}
有什么我可以使用的建议吗?我想这可能真的很简单,但我是初学者,非常感谢:)
[编辑]:空格是唯一的分隔符,通常要替换的字符串不会比原始字符串长。
最佳答案
在这种情况下,我会避免使用 strtok (因为它会修改字符串,作为标记化字符串的副作用),并通过基本上逐个字符地查看字符串并维护一个“读”和“写”索引。由于输出永远不会比输入长,因此写入索引永远不会领先于读取索引,并且您可以“回写”并在同一字符串内进行更改。
为了形象化这一点,我发现在框中写出输入并绘制当前读写索引的箭头并跟踪整个过程很有用,这样您就可以验证您是否拥有一个可以执行您想要执行的操作的系统并且您的循环和索引都按您的预期工作。这是一种与我自己的想法倾向于处理此类算法的方式相匹配的实现。它遍历字符串并向前查找以尝试从当前字符开始匹配。如果找到匹配项,它将替换复制到当前位置,并相应地增加两个索引。
void wordreplace(char * string, const char * search, const char * replace) {
// This is required to be true since we're going to do the replace
// in-place:
assert(strlen(replace) <= strlen(search));
// Get ourselves set up
int r = 0, w = 0;
int str_len = strlen(string);
int search_len = strlen(search);
int replace_len = strlen(replace);
// Walk through the input character by character.
while (r < str_len) {
// Is this character the start of a matching token? It is
// if we see the search string followed by a space or end of
// string.
if (strncmp(&string[r], search, search_len) == 0 &&
(string[r+search_len] == ' ' || string[r+search_len] == '\0')) {
// We matched the search token. Copy the replace token.
memcpy(&string[w], replace, replace_len);
// Update our indexes.
w += replace_len;
r += search_len;
} else {
// Otherwise just copy this character.
string[w++] = string[r++];
}
}
// Be sure to terminate the final version of the string.
string[w] = '\0';
}
(请注意,我调整了您的函数签名以使用更惯用的指针表示法而不是字符数组,并且根据下面的流感注释,我将搜索和替换标记标记为“const”,这是函数广告的一种方式不会修改这些字符串。)
关于c - 在C中替换字符串中的整个单词而不是子字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54914066/