删除c字符串中的字符

时间:2014-08-28 04:13:34

标签: c string

如何从c?

中的字符串中删除特定字符

例如:如果字符串是“abcd”     我需要删除索引1的字符     然后结果应该是“acd”

我的尝试:

void removeSymbol(char *line){ 
    int i,j; char c;
    for(i=0;i<strlen(line);i++){ 
        c = *(line +i); 
        if(!(isdigit(c)||isalpha(c))){ strcpy((line+i),(line+i+1)); } 
    }
    printf("%s\n",line); 
} 

3 个答案:

答案 0 :(得分:1)

static inline void removeSymbol(char *line, size_t index){
    memmove(&line[index], &line[index+1], strlen(&line[index]));
    //printf("%s\n",line); 
}

答案 1 :(得分:0)

我已经更改了removeSymbol API的原型。我希望以下代码符合您的要求

void removeSymbol(char *line, int index)
{ 
    //Added as per comments
    if ( (index > 0 ) && ( index <= strlen (line) ) )
    {

         //index-> index which needs to be removed.
        // +1 is added in memmove last argument to move '\0' character also

        memmove (&line[index-1], line + index, strlen (line)-index +1 );
    }

}

int main(void){

    char symbol [] = "abcdefgh";
    removeSymbol (symbol, 8);
    printf ("%s\n", symbol);
}

答案 2 :(得分:0)

#include <stdio.h>
#include <string.h>
void removSymbol(char *,int);
main()
{
    int index=1;
    removSymbol("abcd",index);
}
void removSymbol(char *line,int index)
{ 
    int i;
    for(i=0;i<strlen(line)-1;i++)
    { 
        if(i<index) 
        {
            *(line+i) = *(line +i);
        }
        else 
        {
            *(line+i) = *(line+i+1);
        }

    }
    *(line+i+1)='\0';
    printf("%s\n",line); 
}