4

Possible Duplicate:
What's the best way to trim std::string

I have a string:

std::string foo = "This is a string    "; // 4 spaces at end

How would I remove the spaces at the end of the string so that it is:

"This is a string" // no spaces at end

please note this is an example and not a representation of my code. I do not want to hard code:

std::string foo = "This is a string"; //wrong
Community
  • 1
  • 1
maffo
  • 1,393
  • 4
  • 18
  • 35
  • This is usually known as `trim`, check out for example http://stackoverflow.com/questions/216823/whats-the-best-way-to-trim-stdstring – Anders Lindahl May 19 '11 at 10:33
  • 7
    Possible dup: [What's the best way to trim std::string](http://stackoverflow.com/q/216823/725163) – e.dan May 19 '11 at 10:33
  • Spaces (ASCII code 32) are not NULL (ASCII code 0). Also: http://stackoverflow.com/questions/1798112/removing-leading-and-trailing-spaces-from-a-string. – AVH May 19 '11 at 10:33

3 Answers3

2

Here you can find a lot of ways to trim the string.

Community
  • 1
  • 1
Vladimir Ivanov
  • 42,730
  • 18
  • 77
  • 103
  • 1
    I wonder why this answer is downvoted... – Vladimir Ivanov May 19 '11 at 10:43
  • 13
    I can't speak for the other downvoter, but I downvoted it because, instead of voting to close as a dupe, you tried to reap rep by linking to the other answer. As a 10k user you should have learned enough of SO to know that closing this as a dupe would have been the proper course of action. (For the same reason I thought I wouldn't need to bother to explain myself.) – sbi May 19 '11 at 14:04
1

First off, NULL chars (ASCII code 0) and whitespaces (ASCII code 32) and not the same thing.

You could use std::string::find_last_not_of to find the last non-whitespace character, and then use std::string::resize to chop off everything that comes after it.

NPE
  • 486,780
  • 108
  • 951
  • 1,012
0
string remove_spaces(const string &s)
{
  int last = s.size() - 1;
  while (last >= 0 && s[last] == ' ')
    --last;
  return s.substr(0, last + 1);
}
Peteris
  • 3,548
  • 4
  • 28
  • 44