views:

194

answers:

6

Hi, i was hoping for some help, opposed to full solutions and i have an idea that i need to know what i am doing wrong when trying to implement

basically i am trying to remove spaces from the end of an array of characters in c

this is what i am doing

i have a method to work out the length of the string and store it in to an int

i set a pointer to point at the first element of my character array

i then set the pointer to the length of the string - 1 (as to not go past the array index of n-1)

if the element here is not a space then i no there are no spaces at the end so i just return the element as a whole

this is where i am stuck, now in the else i no that it must have been a space character ' ' at the end right? without using a library function, how on earth do i remove this space from the string, and proceed with a loop until i meet a character that’s not a ' ' . the looping bit until i meet a character that is not a ' '(space) is easy - its just the removing that’s proving a beast :D

thanks guys - please no solutions though, this is homework and i don’t want to cheat regards

sam

+5  A: 

There are two methods

  1. Treat your string as null terminated, in other words the true end of the string is a '\0' (0x00), then you can simply replace spaces at the end with '\0' until you hit a non-space char.
  2. Determine the length of the new string and copy it. Basically as you work your way back decrement your length until you hit a non-space char (Be careful about an off-by one error here). Finally create a new character array and copy the elements based on this length.

It depends on what you need to do which way is best.

Guvante
+9  A: 

The trick is that a string in C ends with a NUL character (value zero). So you can remove a character from the end of a string by simply overwriting it with the value zero.

Daniel Earwicker
A: 

You can terminate a string by inserting a '\0' where you want it terminated. So, you start at the end, count backwards 'til you find something other than a space, then go back forward one and put in the '\0'.

Jerry Coffin
A: 

Strings, in C, are null terminated.

Ryan Graham
A: 
Sparky
A: 

You know the length of the string, so just start at the end of the string and work backwards. Whenever you encounter a space, just replace it with the null terminating character, \0.