从字符串 C++ 的末尾删除空格字符
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6057245/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Remove space chars from end of string C++
提问by maffo
Possible Duplicate:
What's the best way to trim std::string
可能的重复:
修剪 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
回答by NPE
First off, NULL chars (ASCII code 0) and whitespaces (ASCII code 32) and not the same thing.
首先,NULL 字符(ASCII 代码 0)和空格(ASCII 代码 32)不是一回事。
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.
您可以使用std::string::find_last_not_of
找到最后一个非空白字符,然后使用它std::string::resize
来砍掉后面的所有内容。
回答by Peteris
string remove_spaces(const string &s)
{
int last = s.size() - 1;
while (last >= 0 && s[last] == ' ')
--last;
return s.substr(0, last + 1);
}