Reputation: 245
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.
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 know 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 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
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
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
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
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
Reputation: 19221
There are two methods
It depends on what you need to do which way is best.
Upvotes: 6