knp
knp

Reputation: 89

removing a character in C in Unix is not working

I am trying to remove character 'a' from string in unix Here is my code

#include<stdio.h>
#include<string.h>
int main()
{
   char str[]= "123abcabc123";
   int i;
   for(i=0; i < strlen(str); i++)
   {
     if(str[i]=='a')
       str[i]='\b';
   }
   printf("str is %s\n",str);
   return 0;
}

I am getting output as 12bbc123 instead of "123bcbc123"

Upvotes: 1

Views: 51

Answers (2)

You cannot insert a backspace character like the way you are doing. Unwind has given a good explanation on that.

You are attempting to remove a character from a string INPLACE i.e. without using any extra memory. You could change your for loop to make it work like so:

int j = 0;
for(i=0;i<strlen(str);i++)
{
   if(str[i]=='a')
   {
      continue;
   }
   str[j]=str[i];
   j++;
}
str[j]='\0';

Upvotes: 2

unwind
unwind

Reputation: 399803

You cannot insert the backspace character ('\b') into a string and expect the string to shrink.

It might look shorter when printed, but in memory it's just a string that contains embedded backspace characters.

You need to move the characters after the one you want to remove "backward", i.e. toward lower indexes, so that you overwrite the character you want to remove with its successor in the string, and so on. You can use memmove() for this, but be careful with the lengths. I would recommend pre-computing the string length.

Upvotes: 2

Related Questions