va.
va.

Reputation: 780

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];   
      } 
  }
}

Upvotes: 1

Views: 34827

Answers (5)

Morgoth
Morgoth

Reputation: 11

A faster aproach for those that will find this thread in search for an answer:

void removeChar(char *str, char c) {
    int ofMv = 0, cnt = 0;
    for(; str[cnt] != 0; ofMv++) {
        if(str[ofMv] == c && str[ofMv])
            continue;
        str[cnt] = str[ofMv];
        cnt++;
        if(!str[ofMv])
            return;
    }
}

Better optimized for small uC's, half the size and twice faster:

void removeChar(char *str, char c) {
    char *rS = str;
    char *rD = str;
    for(; *rD != 0; rS++) {
        if(*rS == c && *rS)
            continue;
        *rD = *rS;
        rD++;
        if(!*rS)
            return;
    }
}

This avoids the time for strlen and avoid shifting the right part of the string at each removed character in part, is end of string protected.

Upvotes: 1

Samir
Samir

Reputation: 6605

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

Upvotes: 1

Marco
Marco

Reputation: 57573

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++;
    }
}

Upvotes: 3

Belgi
Belgi

Reputation: 15062

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.

Upvotes: 2

Chowlett
Chowlett

Reputation: 46667

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.

Upvotes: 2

Related Questions