首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 开发语言 > C++ >

怎么去除字符串中的所有空格

2012-05-04 
如何去除字符串中的所有空格boost库里面有一个trim函数,但是是去除首尾空格的有没有一个比较好的方法最好

如何去除字符串中的所有空格
boost库里面有一个trim函数,但是是去除首尾空格的
有没有一个比较好的方法
最好是有现有的函数
或者有比较好的效率高的自己写的也行

[解决办法]

C/C++ code
#include<string>#include<iostream>#include<sstream>#include<vector>using namespace std;void main(){    string name="what's up dude";    istringstream stream(name);    string word;    vector<string> vc;    while(stream>>word)    {        vc.push_back(word);    }     string str;    for(int i = 0; i < vc.size(); ++i)    {        str+=vc[i];    }    cout<<str<<endl;}
[解决办法]
C/C++ code
char *delete_space(char *dest, char *src){    char *rd;    char *wr;        if (NULL == dest || NULL == src)    {        return NULL;    }     for (rd = src; *rd != ' ' && *rd != 0; ++rd)    {        ;    }    wr = rd;    while ((' ' == *rd) ? *rd++ : *wr++ = *rd++)    {        ;    }        return dest;}
[解决办法]
C/C++ code
string delSpace(const string &src){    string newStr;    for_each(src.begin(),src.end(),[&newStr](char ch){        if(ch!=' ')        {            newStr.push_back(ch);        }    });    return newStr;}
[解决办法]
文艺青年通常这样写:

#include <string>
#include <iostream>
#include <functional>
#include <algorithm>

#include <cstring>

using std::string;
using std::ptr_fun;
using std::remove;
using std::cout;

void main()
{
string test(" What's up ");
test.erase(remove_if(test.begin(), test.end(), ptr_fun(isspace)), test.end());
cout << test << "?\n";
}

热点排行