简体   繁体   中英

removing substring from main string with c

I need to remove substring "hello" from the mains string and now I have already replaced 'x' with 'ks' and 'z' with 'ts' as my assignment asked my to do. But now I can't think of a way to remove substrings "hello" and I've tried that with memmove() but after that the printf prints "(null)" .

My code:

#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);
 }

Just a logic error on your side. It prints NULL because after you've removed "hello" , the condition in the while loop gets evaluated again and this leads to:

dest = strstr(dest, c);

which eventually will assign NULL to dest , which is what you print. You need another variable to remember the original string.

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);

This will print you line without "hello" s.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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