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

This question is related to c++ string stl whitespace

The answer is


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

output: 2CF4323CB9DE


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

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

   #include <algorithm>
   using namespace std;

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

Source:

Reference taken from this forum.


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

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

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

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>

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

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

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.


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

output: 2CF4323CB9DE


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

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

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


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

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

string removespace(string str)
{    
    int m = str.length();
    int i=0;
    while(i<m)
    {
        while(str[i] == 32)
        str.erase(i,1);
        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);
}

use it:

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

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.


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


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

output: 2CF4323CB9DE


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.


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

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>

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

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.


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

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

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

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

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.


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


From gamedev

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

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>

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.


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.


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>

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

   #include <algorithm>
   using namespace std;

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

Source:

Reference taken from this forum.


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

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

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

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.


From gamedev

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

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.


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.


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

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

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

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.


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

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

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

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

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

   #include <algorithm>
   using namespace std;

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

Source:

Reference taken from this forum.


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.


From gamedev

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

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

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

   #include <algorithm>
   using namespace std;

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

Source:

Reference taken from this forum.


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

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

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

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

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.


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

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

From gamedev

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

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

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

From gamedev

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

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

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


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

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

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

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.


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

output: 2CF4323CB9DE


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.


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

From gamedev

string.erase(std::remove_if(string.begin(), string.end(), std::isspace), string.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());

From gamedev

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

Examples related to c++

Method Call Chaining; returning a pointer vs a reference? How can I tell if an algorithm is efficient? Difference between opening a file in binary vs text How can compare-and-swap be used for a wait-free mutual exclusion for any shared data structure? Install Qt on Ubuntu #include errors detected in vscode Cannot open include file: 'stdio.h' - Visual Studio Community 2017 - C++ Error How to fix the error "Windows SDK version 8.1" was not found? Visual Studio 2017 errors on standard headers How do I check if a Key is pressed on C++

Examples related to string

How to split a string in two and store it in a field String method cannot be found in a main class method Kotlin - How to correctly concatenate a String Replacing a character from a certain index Remove quotes from String in Python Detect whether a Python string is a number or a letter How does String substring work in Swift How does String.Index work in Swift swift 3.0 Data to String? How to parse JSON string in Typescript

Examples related to stl

Why is it OK to return a 'vector' from a function? How to remove all the occurrences of a char in c++ string How to use the priority queue STL for objects? use std::fill to populate vector with increasing numbers What does iterator->second mean? How to set initial size of std::vector? Sorting a vector in descending order How do I reverse a C++ vector? Recommended way to insert elements into map Replace an element into a specific position of a vector

Examples related to whitespace

How to create string with multiple spaces in JavaScript git: fatal: I don't handle protocol '??http' Show whitespace characters in Visual Studio Code What is the symbol for whitespace in C? How to print variables without spaces between values Trim whitespace from a String How do I escape spaces in path for scp copy in Linux? Avoid line break between html elements Remove "whitespace" between div element How to remove all white spaces in java