從std中刪除空格::在c++中的字符串。

[英]Remove spaces from std::string in C++


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++中,從字符串中刪除空格的首選方法是什么?我可以遍歷所有的字符並構建一個新的字符串,但是有更好的方法嗎?

12 个解决方案

#1


213  

The best thing to do is to use the algorithm remove_if and 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:

現在,算法本身不能更改容器(只修改值),因此它實際上對值進行了重新排列,並返回一個指向當前結束位置的指針。所以我們必須調用字符串::刪除來實際修改容器的長度:

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;
}

#2


69  

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

#3


33  

From gamedev

從gamedev

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

#4


27  

Can you use Boost String Algo? http://www.boost.org/doc/libs/1_35_0/doc/html/string_algo/usage.html#id1290573

你能使用升壓字符串Algo嗎?http://www.boost.org/doc/libs/1_35_0/doc/html/string_algo/usage.html id1290573

erase_all(str, " "); 

#5


12  

For trimming, use boost string algorithms:

對於修邊,使用boost串算法:

#include <boost/algorithm/string.hpp>

using namespace std;
using namespace boost;

// ...

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

#6


11  

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] == '\0' && str[i-1]== ' ')
            {
                str.erase(str.end() - 1);
            }
        }
    }
    return str;
}

#7


10  

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

#8


7  

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, " ", "+");

#9


5  

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.

假設您已經完成了#include

Call it like so:

叫它一樣:

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

#10


2  

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::獨特(s.begin(),s.end(),[](字符,字符f){返回(f = = ' ' | | = = ' ');}),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::獨特(s.begin(),s.end(),[](字符,字符f){返回((f = = ' ' | | = = ' ')| |(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.

但是,正如其他人提到的那樣,“刪除”這個習語似乎也不錯。

#11


0  

string removespace(string str)
{    
    int m = str.length();
    int i=0;
    while(i<m)
    {
        while(str[i] == 32)
        str.erase(i,1);
        i++;
    }    
}

#12


-2  

I'm afraid it's the best solution that I can think of. But you can use reserve() to pre-allocate the minimum required memory in advance to speed up things a bit. You'll end up with a new string that will probably be shorter but that takes up the same amount of memory, but you'll avoid reallocations.

恐怕這是我能想到的最好的解決辦法。但是可以使用reserve()預先分配所需的最小內存,以加快速度。您將得到一個新的字符串,它可能會更短,但是占用相同的內存,但是您將避免重新分配。

EDIT: Depending on your situation, this may incur less overhead than jumbling characters around.

編輯:根據您的情況,這可能比混亂的字符帶來更少的開銷。

You should try different approaches and see what is best for you: you might not have any performance issues at all.

您應該嘗試不同的方法,看看什么對您最好:您可能根本沒有任何性能問題。


注意!

本站翻译的文章,版权归属于本站,未经许可禁止转摘,转摘请注明本文地址:https://www.itdaan.com/blog/2008/09/17/53904e631b6699433a66d0504953a995.html



 
  © 2014-2022 ITdaan.com 联系我们: