2011-05-19 64 views
3

可能重复:
What's the best way to trim std::string删除空间字符

我有一个字符串:

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

这通常被称为'trim',检查出例如http://stackoverflow.com/questions/216823/whats-the-best-way-to-trim-stdstring – 2011-05-19 10:33:01

+7

可能DUP:[这是什么修剪std :: string]的最佳方法(http://stackoverflow.com/q/216823/725163) – 2011-05-19 10:33:25

+0

空格(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

回答

2

Here你可以找到很多的方法来修剪的字符串。

+1

我不知道为什么这个答案是downvoted ... – 2011-05-19 10:43:29

+9

我不能代表其他downvoter说话,但我downvoted,因为,而不是投票关闭的欺骗,你试图通过链接到对方的回答收获代表。作为一个10k的用户,你应该已经学会了足够的知识来知道把它作为一个愚蠢的行为是正确的。 (出于同样的原因,我认为我不需要费心解释我自己。) – sbi 2011-05-19 14:04:00

+0

@sbi。对我感到羞耻。 – 2011-05-19 14:05:11

1

首先,NULL字符(ASCII码0)和空白字符(ASCII码32),而不是同样的事情。

您可以使用std::string::find_last_not_of来查找最后一个非空白字符,然后使用std::string::resize删除它后面的所有内容。

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