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

发布于 2024-07-05 14:51:07 字数 64 浏览 8 评论 0原文

在 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?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(19

赏烟花じ飞满天 2024-07-12 14:51:08
std::string::iterator end_pos = std::remove(str.begin(), str.end(), ' ');
str.erase(end_pos, str.end());
std::string::iterator end_pos = std::remove(str.begin(), str.end(), ' ');
str.erase(end_pos, str.end());
情仇皆在手 2024-07-12 14:51:08

来自 gamedev

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

From gamedev

string.erase(std::remove_if(string.begin(), string.end(), std::isspace), string.end());
沉睡月亮 2024-07-12 14:51:08

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

erase_all(str, " "); 

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

erase_all(str, " "); 
土豪我们做朋友吧 2024-07-12 14:51:08

您可以使用此解决方案来删除字符:

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

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

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());
无远思近则忧 2024-07-12 14:51:08

对于修剪,请使用 boost 字符串算法

#include <boost/algorithm/string.hpp>

using namespace std;
using namespace boost;

// ...

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

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!"
勿忘初心 2024-07-12 14:51:08

嗨,你可以做类似的事情。 该函数删除所有空格。

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

我做了另一个函数,删除所有不必要的空格。

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

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;
}
内心激荡 2024-07-12 14:51:08

在 C++20 中,您可以使用自由函数 std::erase

std::string str = " Hello World  !";
std::erase(str, ' ');

完整示例:

#include<string>
#include<iostream>

int main() {
    std::string str = " Hello World  !";
    std::erase(str, ' ');
    std::cout << "|" << str <<"|";
}

I print | 很明显,开头的空格也被删除了。

注意:这仅删除空格,而不删除所有其他可能被视为空格的字符,请参阅 https://en.cppreference.com/w/cpp/string/byte/isspace

In C++20 you can use free function std::erase

std::string str = " Hello World  !";
std::erase(str, ' ');

Full example:

#include<string>
#include<iostream>

int main() {
    std::string str = " Hello World  !";
    std::erase(str, ' ');
    std::cout << "|" << str <<"|";
}

I print | so that it is obvious that space at the begining is also removed.

note: this removes only the space, not every other possible character that may be considered whitespace, see https://en.cppreference.com/w/cpp/string/byte/isspace

迟月 2024-07-12 14:51:08
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, " ", "+");
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, " ", "+");
治碍 2024-07-12 14:51:08

如果您想使用一个简单的宏来完成此操作,可以使用以下宏:

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

当然,这假设您已经完成了 #include

像这样称呼它:

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

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>
似狗非友 2024-07-12 14:51:08

删除所有 空白字符,例如制表符和换行符 (C++11):

string str = " \n AB cd \t efg\v\n";
str = regex_replace(str,regex("\\s"),"");

Removes all whitespace characters such as tabs and line breaks (C++11):

string str = " \n AB cd \t efg\v\n";
str = regex_replace(str,regex("\\s"),"");
洒一地阳光 2024-07-12 14:51:08
 #include <算法>; 
     使用命名空间 std; 

     int main() { 
         。 
         。 
         s.erase( 删除( s.begin(), s.end(), ' ' ), s.end() ); 
         。 
         。 
     } 
  

资料来源:

参考资料取自论坛。

   #include <algorithm>
   using namespace std;

   int main() {
       .
       .
       s.erase( remove( s.begin(), s.end(), ' ' ), s.end() );
       .
       .
   }

Source:

Reference taken from this forum.

扎心 2024-07-12 14:51:08

我使用了下面的解决方法很长时间 - 不确定它的复杂性。

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=='')||(f=='-' ||s=='-'));}),s.end());

同样,如果您想要删除的字符数不是 1

,而是 增加 ||,其他人提到的擦除删除习语似乎也不错。

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.

ぺ禁宫浮华殁 2024-07-12 14:51:08
string removeSpaces(string word) {
    string newWord;
    for (int i = 0; i < word.length(); i++) {
        if (word[i] != ' ') {
            newWord += word[i];
        }
    }

    return newWord;
}

该代码基本上采用一个字符串并迭代其中的每个字符。 然后它检查该字符串是否是空格,如果不是,则将该字符添加到新字符串中。

string removeSpaces(string word) {
    string newWord;
    for (int i = 0; i < word.length(); i++) {
        if (word[i] != ' ') {
            newWord += word[i];
        }
    }

    return newWord;
}

This code basically takes a string and iterates through every character in it. It then checks whether that string is a white space, if it isn't then the character is added to a new string.

疯到世界奔溃 2024-07-12 14:51:08

只是为了好玩,因为其他答案比这个好得多。

#include <boost/hana/functional/partial.hpp>
#include <iostream>
#include <range/v3/range/conversion.hpp>
#include <range/v3/view/filter.hpp>
int main() {
    using ranges::to;
    using ranges::views::filter;
    using boost::hana::partial;
    auto const& not_space = partial(std::not_equal_to<>{}, ' ');
    auto const& to_string = to<std::string>;

    std::string input = "2C F4 32 3C B9 DE";
    std::string output = input | filter(not_space) | to_string;
    assert(output == "2CF4323CB9DE");
}

Just for fun, as other answers are much better than this.

#include <boost/hana/functional/partial.hpp>
#include <iostream>
#include <range/v3/range/conversion.hpp>
#include <range/v3/view/filter.hpp>
int main() {
    using ranges::to;
    using ranges::views::filter;
    using boost::hana::partial;
    auto const& not_space = partial(std::not_equal_to<>{}, ' ');
    auto const& to_string = to<std::string>;

    std::string input = "2C F4 32 3C B9 DE";
    std::string output = input | filter(not_space) | to_string;
    assert(output == "2CF4323CB9DE");
}
王权女流氓 2024-07-12 14:51:08
  string str = "2C F4 32 3C B9 DE";
  str.erase(remove(str.begin(),str.end(),' '),str.end());
  cout << str << endl;

输出:2CF4323CB9DE

  string str = "2C F4 32 3C B9 DE";
  str.erase(remove(str.begin(),str.end(),' '),str.end());
  cout << str << endl;

output: 2CF4323CB9DE

风情万种。 2024-07-12 14:51:08

我创建了一个函数,用于删除字符串两端的空格。 例如
“Hello World”,将被转换为“Hello world”

其工作原理类似于 python 中经常使用的 striplstriprstrip 函数。

string strip(string str) {
    while (str[str.length() - 1] == ' ') {
        str = str.substr(0, str.length() - 1);
    }
    while (str[0] == ' ') {
        str = str.substr(1, str.length() - 1);
    }
    return str;
}

string lstrip(string str) {
    while (str[0] == ' ') {
        str = str.substr(1, str.length() - 1);
    }
    return str;
}

string rstrip(string str) {
    while (str[str.length() - 1] == ' ') {
        str = str.substr(0, str.length() - 1);
    }
    return str;
}

I created a function, that removes the white spaces from the either ends of string. Such as
" Hello World ", will be converted into "Hello world".

This works similar to strip, lstrip and rstrip functions, which are frequently used in python.

string strip(string str) {
    while (str[str.length() - 1] == ' ') {
        str = str.substr(0, str.length() - 1);
    }
    while (str[0] == ' ') {
        str = str.substr(1, str.length() - 1);
    }
    return str;
}

string lstrip(string str) {
    while (str[0] == ' ') {
        str = str.substr(1, str.length() - 1);
    }
    return str;
}

string rstrip(string str) {
    while (str[str.length() - 1] == ' ') {
        str = str.substr(0, str.length() - 1);
    }
    return str;
}
北风几吹夏 2024-07-12 14:51:08
string removespace(string str)
{    
    int m = str.length();
    int i=0;
    while(i<m)
    {
        while(str[i] == 32)
        str.erase(i,1);
        i++;
    }    
}
string removespace(string str)
{    
    int m = str.length();
    int i=0;
    while(i<m)
    {
        while(str[i] == 32)
        str.erase(i,1);
        i++;
    }    
}
瑾夏年华 2024-07-12 14:51:08

恐怕这是我能想到的最好的解决方案。 但是您可以使用 Reserve() 提前预先分配所需的最小内存,以加快速度。 您最终会得到一个新字符串,该字符串可能会更短,但占用相同数量的内存,但您将避免重新分配。

编辑:根据您的情况,这可能会比乱七八糟的字符产生更少的开销。

您应该尝试不同的方法,看看什么最适合您:您可能根本不会遇到任何性能问题。

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.

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.

差↓一点笑了 2024-07-12 14:51:07

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

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

现在算法本身无法更改容器(只能修改值),因此它实际上会打乱值并返回一个指向现在应该结束的位置的指针。 因此,我们必须调用 string::erase 来实际修改容器的长度:

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

我们还应该注意,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;
}

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

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;
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文