【问题标题】:How to replace substring in a string with another string in C? [duplicate]如何用C中的另一个字符串替换字符串中的子字符串? [复制]
【发布时间】:2021-05-09 05:26:02
【问题描述】:

例如,我想将123abc890 中的abc 替换为xyz。如果不使用#include <string.h>,我将如何做到这一点。

我尝试通过创建一个新字符串来尝试此操作,并且在 for 循环的帮助下,我会将每个字符复制到新字符串中。但是,我似乎无法找到如何去做这件事。任何方法都可以,但是我不能使用#include <string.h>

char str1[] = "123abc890";
char str2[] = "abc";
char str3[] = "xyz";
char new_string[50];

for (int i = 0; str1[i] != '\0'; i++) {
    if (str1[i] == str2[i]) {
        for (int j = 0; str2[j] != '\0'; j++) {
            if (str1[i+j] != str1[i+j]) {
                break:
            }
            new_string[i] = str3[i];
        }
    }
    new_string[i] = str1[i];
}

仅供参考,我对 C 很陌生,所以要小心一些非常笨拙的代码。

【问题讨论】:

  • 请显示minimal reproducible example。这只是一个无法编译的代码片段。
  • 将问题分解为更小的步骤。为有意义的人编写函数。例如,首先编写一个接受str1str2 的函数,然后返回str1 中与str2 匹配的第一个索引(如果有) - 即基本上重写strstr
  • 此外,如果您不允许使用 string.h 中的函数,您可以编写自己的版本。其中许多是一两个衬垫。
  • 先尝试在纸上制定算法。这里的循环和索引没有多大意义。仅仅因为str1[i] == str2[0] 并不意味着你有一个完整的子字符串,所以如果你要冲过去开始复制那个子字符串,就像你做的那样,准备好在整个子字符串不匹配时撤消它。编写一个助手来检查 str2 和 str 之间的完整子字符串匹配,并在 str1 的每个索引上尝试它。当它返回 true 时,您可以安全地将 str2 复制到目的地,否则复制 str1 的字符。

标签: c replace


【解决方案1】:

你的代码是一个好的开始,但是有很多问题:

  • 测试if (str1[i+j] != str1[i+j]) 始终为真
  • 您复制不完整的片段,复制后未能跳过。
  • 您忘记将目的地设为空。

这是修改后的版本:

#include <stdio.h>

char *str_replace(char *dest, const char *str1, const char *str2, const char *str3) {
    size_t i = 0, j, k = 0;
    
    // replacing substring `str2` with `str3`, assuming sufficient space
    while (str1[i] != '\0') {
        for (j = 0; str2[j] != '\0'; j++) {
            if (str1[i + j] != str2[j]) {
                break;
            }
        }
        if (str2[j] == '\0' && j > 0) {
            // we have a match: copy the replacement and skip it
            i += j;
            for (j = 0; str3[j] != '\0'; j++) {
                dest[k++] = str3[j];
            }
        } else {
            // copy the byte and skip it.
            dest[k++] = str1[i++];
        }
    }
    dest[k] = '\0';  // null terminate the destination
    return dest;
}

int main() {
    char new_string[50];
    printf("%s\n", str_replace(new_string, "123abc890", "abc", "abc"));
    printf("%s\n", str_replace(new_string, "123abc890", "abc", "xyz"));
    printf("%s\n", str_replace(new_string, "123abc890", "a", "xyz"));
    printf("%s\n", str_replace(new_string, "123abc890", "abc", ""));
    return 0;
}

输出:

123abc890 123xyz890 123xyzbc890 123890

【讨论】:

  • 好电话,行之有效。
猜你喜欢
  • 1970-01-01
  • 2011-06-06
  • 1970-01-01
  • 2012-12-18
  • 2011-04-06
  • 2014-06-03
  • 1970-01-01
  • 1970-01-01
  • 2021-06-15
相关资源
最近更新 更多