How to remove all occurrences of a given character from string in C?

后端 未结 7 592
有刺的猬
有刺的猬 2020-11-30 11:24

I\'m attempting to remove a character from a string in C. The problem I am having with my code is that it removes the first instance of the character from the string but als

7条回答
  •  北海茫月
    2020-11-30 11:51

    i know that it is a type of duplicate answer, but this code is function's version for solving the problem. I thought that as the questioner was a beginner, he might learn much from decomposed version of problem.

    int del_x_char(char *p, int x)
    {
        char *q;
        x=first_occurance(p, 'i')/*you can replace any character that you want delete with 'i'*/
        q=p+x;
        while(*q=*(q+1))
            q++;
        *q='\0';
        return 0;
    }
    int first_occurance(char *q, char phar)
    {
        int i=0;
        while(*q)
        {   
            if(*q++==phar)
                return i;
            i++;
        }
        return -1;
    }
    

提交回复
热议问题