Alex Rivera | Logout

remove all occurences of a character in C string - Example needed

Asked 2010-11-12T05:14:02.693
9

InputString: "I am unwell" "We need to go to the doctor" "How long will it take?".

OutputString: I am unwell We need to go to the doctor How long will it take?

The string needs to cleaned of all occurrences of the char " . I can think of the following approacg

  1. Use, strchr() function finding first occurrence of "
  2. Move all characters in the string left by once position.

Repeat steps 1 and 2 , until strchr() returns a NULL pointer.

I feel this is very inefficient way to approach this problem. I need to know , if there are other methods to achieve this? Pseudo code or actual code will both be appreciated.

Edit
Report

1 Answer

0

If your string is not very big, the obvious answer would be to have a separate string. A single loop till you get \0 (End of string) Have a loop (Gives you O(n)) and a comparison to check if the current location of the string is the character in question (again O(n) )

In all :


  s1 = original array
  s2 = new array to store the final result
  c = character in question.  
  current_pointer = 0 
  new_pointer =0 
  while(s1[current_pointer] != '\0') {
   ele = s1[current_pointer] ;

   if( ele != c)  { 
    s2[new_pointer++] = ele
   }
    current_pointer++
  }

Note that this method works only when string sizes are small. We need to go for better methods as size of string increases.

Hope this helps.

answered 2010-11-12T05:32:31.030

Your Answer