簡體   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