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++;
}
}
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With