我有一个字符串:
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
我有一个字符串:
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
首先,NULL字符(ASCII码0)和空白字符(ASCII码32),而不是同样的事情。
您可以使用std::string::find_last_not_of
来查找最后一个非空白字符,然后使用std::string::resize
删除它后面的所有内容。
string remove_spaces(const string &s)
{
int last = s.size() - 1;
while (last >= 0 && s[last] == ' ')
--last;
return s.substr(0, last + 1);
}
这通常被称为'trim',检查出例如http://stackoverflow.com/questions/216823/whats-the-best-way-to-trim-stdstring – 2011-05-19 10:33:01
可能DUP:[这是什么修剪std :: string]的最佳方法(http://stackoverflow.com/q/216823/725163) – 2011-05-19 10:33:25
空格(ASCII码32)不为NULL(ASCII码0)。另外:http://stackoverflow.com/questions/1798112/removing-leading-and-trailing-spaces-from-a-string。 – Darhuuk 2011-05-19 10:33:33