Alex Rivera | Logout

Remove spaces from a string, but not at the beginning or end

Asked 2010-02-17T10:01:30.993
11

I am trying to remove spaces from a string in C, not from the end, nor the beginning, just multiple spaces in a string

For example

hello  everyone this     is a test

has two spaces between hello and everyone, and five spaces from this to is. Ultimately I would want to remove 1 space from the 2 and 4 from the 5, so every gap has 1 space exactly. Make sense?

This is what I was going to do:

  • create a pointer, point it to the string at element 1 char[0].

  • do a for loop through the length of the string

  • then my logic is, if my pointer at [i] is a space and my pointer at element [i+1] space then to do something

I am not quite sure what would be a good solution from here, bearing in mind I won't be using any pre-built functions. Does anyone have any ideas?

Edit
Report

1 Answer

4

One way is to do it in-place. Loop through the string from the beginning to end. store a write pointer and a read pointer. Each loop the write pointer and read pointer advances by one. When you encounter a space transfer it as normal but then loop the read pointer incrementing each time until a non-space is found (Or the end of the string, obviously). Don't forget to add a '\0' at the end and you now have the same string without the spaces.

answered 2010-02-17T10:04:35.217

Your Answer