C中的调试字符串替换功能

Cha*_* Le 2 c string debugging

我尝试编写一个函数,在给定的字符串s中将所有字符串s1替换为s2.但是,我不知道为什么我的程序在替换函数中的行*p = 0处停止而没有报告任何错误?@@

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


void replace(char * s, char * s1, char * s2) {
    char * p; int l=strlen(s2);
    while ((p=strstr(s,s1))) {
        *p=0;
        p+=l;
        strcat(s,s2);
        strcat(s,p);
    }
}    

int main(void) {    
    char *s=(char *)"cmd=ls+-la&abc=xyz";
    replace (s, "+", " ");    
    printf("%s", s);
    return EXIT_SUCCESS;    
}
Run Code Online (Sandbox Code Playgroud)

Wiz*_*Wiz 5

替换函数存在一些问题,但首先,指向常量char数组的指针与字符数组之间存在很大差异:

char *str = "some string";
Run Code Online (Sandbox Code Playgroud)

分配str不可变字符数组的地址(只读),它不复制字符串,只涉及指针.任何修改该字符串的尝试都将导致未定义的行为.

char str[] = "some string";
Run Code Online (Sandbox Code Playgroud)

在这种情况下str,一个数组(大小足以容纳字符串+\0)初始化为该字符串,允许修改数组中的单个字符.

返回替换功能.

我将从我看到的第一件事开始,你使用strstrstrcat循环内部是非常低效的.每次调用strstr时,它都从字符串的开头开始,并搜索第一个出现的第二个字符串,同样的问题可以看出strcat每次都需要找到null-terminator.

我看到的另一个问题是,如果替换字符串(s2)比原始字符串(s1)长,则必须移动整个字符串以适应新字符串的其他字符.如果替换字符串较短,则会出现同样的问题.

替换简单char的基本方法可能如下所示:

while (*s)
{
    if (*s == c1)
        *s = c2;
    ++s;
}
Run Code Online (Sandbox Code Playgroud)

替换字符串的一个更复杂的方法是:

/* PRECONDITION: strlen(s1) == strlen(s2) */
int l = strlen(s2);

while (*s)
{
    if (!strncmp(s, s1, l))
    {
        memcpy(s, s2, l);
        s += l;
    }
    else
        ++s;
}
Run Code Online (Sandbox Code Playgroud)