如何用另一个子字符串替换字符串的一部分

jac*_*y43 2 c string.h

我需要将字符串“ on”替换为“ in”,strstr()函数返回一个指向字符串的指针,所以我想将新值分配给该指针可以工作,但没有成功

#include <stdio.h>
#include <string.h>

int main(void) {
    char *m = "cat on couch";
    *strstr(m, "on") = "in";
    printf("%s\n", m);
}
Run Code Online (Sandbox Code Playgroud)

chq*_*lie 5

如果两个子串的长度相同,则用另一个子串替换很容易:

  • 用以下命令定位子字符串的位置 strstr
  • 如果存在,请使用memcpy新的子字符串覆盖它。
  • 用分配指针*strstr(m, "on") = "in";不正确,应生成编译器警告。可以避免这样的错误gcc -Wall -Werror
  • 但是请注意,您不能修改字符串文字,需要定义一个初始化数组,char以便可以对其进行修改。

这是更正的版本:

#include <stdio.h>
#include <string.h>

int main(void) {
    char m[] = "cat on couch";
    char *p = strstr(m, "on");
    if (p != NULL) {
        memcpy(p, "in", 2);
    }
    printf("%s\n", m);
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

如果替换的时间较短,则代码会稍微复杂一些:

#include <stdio.h>
#include <string.h>

int main(void) {
    char m[] = "cat is out roaming";
    char *p = strstr(m, "out");
    if (p != NULL) {
        memcpy(p, "in", 2);
        memmove(p + 2, p + 3, strlen(p + 3) + 1);
    }
    printf("%s\n", m);
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

在一般情况下,它甚至更加复杂,并且数组必须足够大以适应长度差:

#include <stdio.h>
#include <string.h>

int main(void) {
    char m[30] = "cat is inside the barn";
    char *p = strstr(m, "inside");
    if (p != NULL) {
        memmove(p + 7, p + 6, strlen(p + 6) + 1);
        memcpy(p, "outside", 7);
    }
    printf("%s\n", m);
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

这是处理所有情况的通用函数:

#include <stdio.h>
#include <string.h>

char *strreplace(char *s, const char *s1, const char *s2) {
    char *p = strstr(s, s1);
    if (p != NULL) {
        size_t len1 = strlen(s1);
        size_t len2 = strlen(s2);
        if (len1 != len2)
            memmove(p + len2, p + len1, strlen(p + len1) + 1);
        memcpy(p, s2, len2);
    }
    return s;
}

int main(void) {
    char m[30] = "cat is inside the barn";

    printf("%s\n", m);
    printf("%s\n", strreplace(m, "inside", "in"));
    printf("%s\n", strreplace(m, "in", "on"));
    printf("%s\n", strreplace(m, "on", "outside"));
    return 0;
}
Run Code Online (Sandbox Code Playgroud)