我有一个字符串:
std::string foo = "This is a string "; // 4 spaces at end
如何删除字符串末尾的空格,使其为:
"This is a string" // no spaces at end
请注意这是一个示例,而不是我的代码的表示。我不想硬编码:
std::string foo = "This is a string"; //wrong
答案 0 :(得分:2)
Here你可以找到许多修剪字符串的方法。
答案 1 :(得分:1)
首先,NULL字符(ASCII代码0)和空格(ASCII代码32)并不是一回事。
您可以使用std::string::find_last_not_of
查找最后一个非空白字符,然后使用std::string::resize
来删除之后的所有内容。
答案 2 :(得分:0)
string remove_spaces(const string &s)
{
int last = s.size() - 1;
while (last >= 0 && s[last] == ' ')
--last;
return s.substr(0, last + 1);
}