繁体   English   中英

用 c 从主字符串中删除子字符串

[英]removing substring from main string with c

我需要从主字符串中删除子字符串"hello" ,现在我已经按照我的作业要求将'x'替换为'ks' ,将'z'替换为'ts' 但是现在我想不出删除子字符串"hello" ,我已经用memmove()尝试过,但之后 printf 打印"(null)"

我的代码:

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

void antikorso(char *dest, const char *src) {
    const char *p = src;
    int i;

    for (i = 0; *p != '\0'; i++, p++)
    {
        if (*p == 'x') {
            dest[i++] = 'k';
            dest[i] = 's';
        }
        else if (*p == 'z') {
            dest[i++] = 't';
            dest[i] = 's';
        }
        else
        {
            dest[i] = *p;
        }
    }

    dest[i] = '\0';
    printf("\n%s", dest);
    char c[10] = "hello";
    int j;
    while (dest = strstr(dest, c))
        memmove(dest, dest + strlen(c), 1 + strlen(dest + strlen(c)));

    printf("\n%s", dest);
}


int main(void)
{

     const char *lol = "yxi izexeen hello asd hello asd";
     char asd[1000];
     antikorso(asd, lol);
 }

只是你这边的逻辑错误。 它打印NULL因为在您删除"hello"while循环中的条件将再次评估,这导致:

dest = strstr(dest, c);

最终会将NULL分配给dest ,这就是您打印的内容。 您需要另一个变量来记住原始字符串。

char *original = dest;
char c[10] = "hello";
while (dest = strstr(dest, c))
    memmove(dest, dest + strlen(c), 1 + strlen(dest + strlen(c)));

printf("\n%s", original);

这将打印没有"hello"的行。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM