在c++中,从字符串中删除空格的首选方法是什么?我可以循环遍历所有字符,并建立一个新的字符串,但有更好的方法吗?


当前回答

# include <算法> 使用命名空间std; Int main() { . . s.erase(删除(s.begin (), s.end (), ' ' ), s.end ()); . . }


来源:

参考资料来自本论坛。

其他回答

string removespace(string str)
{    
    int m = str.length();
    int i=0;
    while(i<m)
    {
        while(str[i] == 32)
        str.erase(i,1);
        i++;
    }    
}
string replaceinString(std::string str, std::string tofind, std::string toreplace)
{
        size_t position = 0;
        for ( position = str.find(tofind); position != std::string::npos; position = str.find(tofind,position) )
        {
                str.replace(position ,1, toreplace);
        }
        return(str);
}

使用它:

string replace = replaceinString(thisstring, " ", "%20");
string replace2 = replaceinString(thisstring, " ", "-");
string replace3 = replaceinString(thisstring, " ", "+");

对于微调,使用boost字符串算法:

#include <boost/algorithm/string.hpp>

using namespace std;
using namespace boost;

// ...

string str1(" hello world! ");
trim(str1);      // str1 == "hello world!"

你能使用Boost String算法吗?http://www.boost.org/doc/libs/1_35_0/doc/html/string_algo/usage.html#id1290573

erase_all(str, " "); 

你可以使用这个解决方案来删除一个字符:

#include <algorithm>
#include <string>
using namespace std;

str.erase(remove(str.begin(), str.end(), char_to_remove), str.end());