简体   繁体   中英

C remove chars from string

I have to write a function in C , which deletes all characters from string which are equal to entered character. For example user enters string "aabbccaabbcc" and char 'b' then the result should be "aaccaacc". I can't find mistake in my code (function does not delete all characters that should be deleted):

void removechar( char str[], char t )
{
  int i,j;
  for(i=0; i<strlen(str); i++)
  {
    if (str[i]==t) 
      for (j=i; j<strlen(str); j++)
      {
        str[j]=str[j+1];   
      } 
  }
}

When you delete one char (say at index = 5) at that index now correspond char that was at index = 6; but your for cycle increment to index = 6, so you skip new char at index = 5.
You'd better copy to a new string valid chars, it's easier.
Or you can try

void removechar( char str[], char t )
{
    int i,j;
    i = 0;
    while(i<strlen(str))
    {
        if (str[i]==t) 
        { 
            for (j=i; j<strlen(str); j++)
                str[j]=str[j+1];   
        } else i++;
    }
}

Here is my function

const char *removeCommaFromString(char *str){
int i,j;
i = 0;
while(i<strlen(str))
{
    if (str[i]==',')
    {
        for (j=i; j<strlen(str); j++)
            str[j]=str[j+1];
    }
    else i++;
}
return str;

}

Usage

char sam[]= {"Samir, Samedov"};
char * sss;
sss = removeComma(sam);

printf("\n%s",sam);

Output : Samir Samedov

Since this looks like a homework exercise, I'll just give you a hint. Think about what happens to your string and loop counters when you have two adjacent of the character to remove.

You can't remove chars from a string in this way. What you want to do is create a new string (char* array) and copy chars unless the char is t. in this case comtinue to the next char.

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