Remove spaces from std::string in C++

2019-01-01 06:04发布

What is the preferred way to remove spaces from a string in C++? I could loop through all the characters and build a new string, but is there a better way?

标签: c++ stl
12条回答
步步皆殇っ
2楼-- · 2019-01-01 06:45

For trimming, use boost string algorithms:

#include <boost/algorithm/string.hpp>

using namespace std;
using namespace boost;

// ...

string str1(" hello world! ");
trim(str1);      // str1 == "hello world!"
查看更多
不流泪的眼
3楼-- · 2019-01-01 06:46

I used the below work around for long - not sure about its complexity.

s.erase(std::unique(s.begin(),s.end(),[](char s,char f){return (f==' '||s==' ');}),s.end());

when you wanna remove character ' ' and some for example - use

s.erase(std::unique(s.begin(),s.end(),[](char s,char f){return ((f==' '||s==' ')||(f=='-'||s=='-'));}),s.end());

likewise just increase the || if number of characters you wanna remove is not 1

but as mentioned by others the erase remove idiom also seems fine.

查看更多
还给你的自由
4楼-- · 2019-01-01 06:50

You can use this solution for removing a char:

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

str.erase(remove(str.begin(), str.end(), char_to_remove), str.end());
查看更多
余生无你
5楼-- · 2019-01-01 06:53
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);
}

use it:

string replace = replaceinString(thisstring, " ", "%20");
string replace2 = replaceinString(thisstring, " ", "-");
string replace3 = replaceinString(thisstring, " ", "+");
查看更多
牵手、夕阳
6楼-- · 2019-01-01 07:00
弹指情弦暗扣
7楼-- · 2019-01-01 07:01

If you want to do this with an easy macro, here's one:

#define REMOVE_SPACES(x) x.erase(std::remove(x.begin(), x.end(), ' '), x.end())

This assumes you have done #include <string> of course.

Call it like so:

std::string sName = " Example Name ";
REMOVE_SPACES(sName);
printf("%s",sName.c_str()); // requires #include <stdio.h>
查看更多
登录 后发表回答