leo
leo

Reputation: 245

Trimming a string in C (without using library functions)

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 where I am stuck, now in the else I know 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 - it's just the removing that’s proving a beast.

Please no full solutions though, since this is homework and I don’t want to cheat.

Upvotes: 3

Views: 1187

Answers (6)

user266117
user266117

Reputation: 56

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.

Upvotes: 0

Sparky
Sparky

Reputation: 14117

Strings in C are terminated with the '\0' character.

If you have a character pointer

, then ...

   *p = 'c';                    and
   *(p  + 0) = 'c';             and
   p[0] = 'c';

will all write 'c' to the byte pointed to by

.

Continuing with this theme ...

   *(p + 1) = 'c';              and
   p[1] = 'c';

will both write 'c' to the byte following that pointed to by

.

Upvotes: 0

Ryann Graham
Ryann Graham

Reputation: 8209

Strings, in C, are null terminated.

Upvotes: 0

Jerry Coffin
Jerry Coffin

Reputation: 490663

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'.

Upvotes: 0

Daniel Earwicker
Daniel Earwicker

Reputation: 116744

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.

Upvotes: 9

Guvante
Guvante

Reputation: 19221

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.

Upvotes: 6

Related Questions