Remove Spaces from String in C++

In this article, we will discuss different ways to remove all spaces from a string in C++.

Table Of Contents

Remove spaces from a string using remove() and string::erase()

In C++, a string is a collection of characters, and it has all the features of a container. Therefore, STL Algorithms built for containers can work for strings too.

The Standard Template Library provides a function std::remove() i.e.

template <class ForwardIterator, class T>
  ForwardIterator remove (ForwardIterator first, ForwardIterator last, const T& val);

It accepts a range (first & last iterator of a container) and a value as arguments. Then it shifts all the occurrences of the given element to the end of the container and returns an iterator pointing to the new end i.e., the start of the segment where all matching elements are shifted.

Advertisements

We can use the remove() function to shift all occurrences of a given character to the end of the string. Then using the string::erase() function, we can delete this segment from the end of the string. For that, we need to pass two arguments to the string::erase() function,

  1. An iterator returned by remove() function
  2. An iterator pointing to the end of the string.

The string::erase() function will remove the characters in the provided range. Let’s learn a little bit more about the string::erase() function,

iterator string::erase(iterator first, iterator last);

One of the overloaded versions of string::erase() functions accepts two iterators as arguments and deletes the sequence of characters in the range [first,last).

So, to delete all occurrences of a character from a string, we can call the remove() function to shift the matching characters to the end of the string. Then call the string::erase() function to delete that part of the string.

Let’s use this to remove all occurrences of spaces from the string i.e.

#include <iostream>
#include <algorithm>

int main()
{
    std::string sampleStr = " This is Some String ";

    // Remove all spaces from the string
    sampleStr.erase(std::remove(sampleStr.begin(),
                                sampleStr.end(),
                                ' '),
                    sampleStr.end());

    std::cout<< sampleStr << std::endl;

    return 0;
}

Output:

ThisisSomeString

It removed all the occurrences of spaces from the string.

Remove spaces from a string using std::erase() in C++20

The C++20 introduced a new STL Algorithm, std::erase(container, element), to delete all occurrences of an element from a container. It accepts two arguments,

  1. An STL Container from which we need to delete elements
  2. Value of the element to be deleted

It deletes all occurrences of a given element from the container.

To delete the spaces from a string, we can use erase() function. As string is also a container of characters, so we can pass the string and the character to be deleted as argument in the erase() function. For example,

#include <iostream>
#include <algorithm>
#include <vector>

int main()
{
    std::string sampleStr = " This is Some String ";

    // Remove all spaces from the string
    std::erase(sampleStr, ' ');

    std::cout<< sampleStr << std::endl;


    return 0;
}

Output:

ThisisSomeString

It removed all the occurrences of spaces from the string.

Important Note:

As std::erase() is introduced in C++20, so to compile this code with g++ or gcc use this command,

g++ --std=c++2a  temp.cpp

Remove spaces from a string using regex in C++

In C++, the regex provides a function regex_replace() to replace the contents in string. In one of its overloaded version, it accepts three arguments,

string regex_replace(string, regex_pattern, replacement_string)

Parameters

  1. String from which we need to replace the characters.
  2. The regex pattern is based on which sub-strings will be matched in the string.
  3. The replacement string that will replace the matched substrings.

It returns a new string object with the replaced contents.

To delete the spaces from a string, we can use regex_replace() function with following arguments,

  • String from which we need to remove the spaces.
  • A regex pattern that will match all the spaces in the string i.e. “\s”.
  • An empty string as the replacement string

For example,

#include <iostream>
#include <regex>

int main()
{
    std::string sampleStr = " This is Some String ";

    // Remove all spaces from the string
    sampleStr = std::regex_replace( sampleStr,
                                    std::regex("\\s"),
                                    "");

    std::cout<< sampleStr << std::endl;


    return 0;
}

Output:

ThisisSomeString

It removed all the occurrences of spaces from the string.

Summary:

We learned about three different ways to delete all spaces from a string in C++.

Do you want to Learn Modern C++ from best?

We have curated a list of Best C++ Courses, that will teach you the cutting edge Modern C++ from the absolute beginning to advanced level. It will also introduce to you the word of Smart Pointers, Move semantics, Rvalue, Lambda function, auto, Variadic template, range based for loops, Multi-threading and many other latest features of C++ i.e. from C++11 to C++20.

Check Detailed Reviews of Best Modern C++ Courses

Remember, C++ requires a lot of patience, persistence, and practice. So, start learning today.

Leave a Comment

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Scroll to Top