从 C++ 中的 std::string 中删除空格

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/83439/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-27 12:44:00  来源:igfitidea点击:

Remove spaces from std::string in C++

c++stl

提问by Steve Hanov

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++ 中从字符串中删除空格的首选方法是什么?我可以遍历所有字符并构建一个新字符串,但是有更好的方法吗?

回答by Matt Price

The best thing to do is to use the algorithm remove_ifand isspace:

最好的办法是使用算法remove_if和isspace:

remove_if(str.begin(), str.end(), isspace);

Now the algorithm itself can't change the container(only modify the values), so it actually shuffles the values around and returns a pointer to where the end now should be. So we have to call string::erase to actually modify the length of the container:

现在算法本身不能改变容器(只能修改值),所以它实际上对值进行了混洗并返回一个指向现在结束位置的指针。所以我们必须调用 string::erase 来实际修改容器的长度:

str.erase(remove_if(str.begin(), str.end(), isspace), str.end());

We should also note that remove_if will make at most one copy of the data. Here is a sample implementation:

我们还应该注意到 remove_if 最多只能复制一份数据。这是一个示例实现:

template<typename T, typename P>
T remove_if(T beg, T end, P pred)
{
    T dest = beg;
    for (T itr = beg;itr != end; ++itr)
        if (!pred(*itr))
            *(dest++) = *itr;
    return dest;
}

回答by Arno

std::string::iterator end_pos = std::remove(str.begin(), str.end(), ' ');
str.erase(end_pos, str.end());

回答by rupello

From gamedev

来自游戏开发

string.erase(std::remove_if(string.begin(), string.end(), std::isspace), string.end());

回答by Nemanja Trifunovic

回答by Roman

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!"

回答by user2281802

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());

回答by ddacot

Hi, you can do something like that. This function deletes all spaces.

你好,你可以这样做。此函数删除所有空格。

string delSpaces(string &str) 
{
   str.erase(std::remove(str.begin(), str.end(), ' '), str.end());
   return str;
}


I made another function, that deletes all unnecessary spaces.

我做了另一个功能,删除所有不必要的空间。

string delUnnecessary(string &str)
{
    int size = str.length();
    for(int j = 0; j<=size; j++)
    {
        for(int i = 0; i <=j; i++)
        {
            if(str[i] == ' ' && str[i+1] == ' ')
            {
                str.erase(str.begin() + i);
            }
            else if(str[0]== ' ')
            {
                str.erase(str.begin());
            }
            else if(str[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);
}
' && str[i-1]== ' ') { str.erase(str.end() - 1); } } } return str; }

回答by SudoBash

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

use it:

用它:

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

回答by Volomike

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

如果你想用一个简单的宏来做到这一点,这里有一个:

std::string sName = " Example Name ";
REMOVE_SPACES(sName);
printf("%s",sName.c_str()); // requires #include <stdio.h>

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

#include <string>当然假设您已经完成了。

Call it like so:

像这样称呼它:

##代码##

回答by RaGa__M

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());

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());

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

同样,||如果您要删除的字符数不是 1 ,则只需增加

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

但正如其他人所提到的,擦除删除习语似乎也不错。