首页 > 解决方案 > 删除字符串中所有出现的子字符串

问题描述

该函数接收一个字符串和一个子字符串,并应删除字符串中所有出现的该子字符串。例如,

string = hello world
substring = hello 

该函数应该只打印“ world

我应该指出,我必须只使用指针来解决这个问题

我已经尝试过了,但它只删除了子字符串第一个字母的出现。

char* del_all_substr(char *pstr, char *psub){

    char *pr = pstr;
    char *pw = pstr;

    while (*pr){
        for (int i = 0; i <strlen(psub);i++) {
            *pw = *pr++;
            pw += (*pw != *(psub+i));
        }
        *pw = '\0';
    }
}
int main_tp06(int argc, const char *argv[]){

    char str[] = "hello world";
    char sub[] = "hello";

    del_all_substr(str,sub);
    printf("%s",str);
    return 0 ;
}

标签: cstringpointers

解决方案


you could use strstr repeatedly to find all occurrences of the string. For example consider this string "Hello world, Hello world", and say that we want to move all occurrences of "Hello" from the string. You can use strstr to find the first instance of "Hello", after that you can overwrite it by moving everything in the string back using memmove (make sure you move the nul terminator as well), repeat again and again until strstr returns no matches. You could also avoid this approach by instead allocating your own string that is at least strlen(pstr) bytes long and then copying data from pstr byte by byte and not copying the bytes that match psub


推荐阅读