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 
3

3 Answers 3

1

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

Sign up to request clarification or add additional context in comments.

2 Comments

I wonder why this answer is downvoted...
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.)
0

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.

Comments

-1
string remove_spaces(const string &s) { int last = s.size() - 1; while (last >= 0 && s[last] == ' ') --last; return s.substr(0, last + 1); } 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.