Remove Newline Characters from a String in C++

In this article, we will discuss different ways to remove all newline characters from a string in C++. The new line characters can be ‘\n’ or ‘\r’.

Table of Characters

Remove Newline characters from String using Regex

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.

We can use the regex_replace() function to remove all newline characters from string. For that we need to pass these three arguments
to the regex_replace() function,

Advertisements
  1. String from which we need to remove characters
  2. A regex pattern that matches all the occurrences new characters i.e. “\r\n|\r|\n”.
  3. An empty string as the replacement string.

It will replace the occurrences of matched characters with empty string. Basically it will delete all newline characters from the string. For example,

#include <iostream>
#include <regex>

int main()
{
    std::string sampleStr =
        "This is Some String \n\n\r\n some text \r\n Another Text \n\n The end";

    // Remove newline characters from string in C++
    sampleStr = std::regex_replace( sampleStr,
                                    std::regex("\\r\\n|\\r|\\n"),
                                    "");

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

    return 0;
}

Output:

This is Some String  some text  Another Text  The end

It removed all newline characters from the string.

Remove Newline characters from String using remove_if() and std::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_if() i.e.

template <class ForwardIterator, class UnaryPredicate>
  ForwardIterator remove_if (ForwardIterator first, ForwardIterator last, UnaryPredicate pred);

It accepts a range (first & last iterator of a container) and a unary callback function as arguments. Then iterates over all the elements in the range. While iteration, it calls the callback function pred() for each element of the range. It then shifts the elements for which the callback function returns true to the end of the container. It returns an iterator pointing to the new end, i.e., the segment’s start where all selected elements are shifted.

We can use the remove_if() function to shift specific elements to the end of the string based on conditions. 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 characters from a string based on conditions, we can call the remove_if() and string::erase() functions.

Let’s use the remove_if() and string::erase() function to remove all newline characters from string. For example,

#include <iostream>
#include <algorithm>

int main()
{
    std::string sampleStr =
        "This is Some String \n\n\r\n some text \r\n Another Text \n\n The end";

    // Remove newline characters from string in C++
    sampleStr.erase(std::remove_if( sampleStr.begin(),
                                    sampleStr.end(),
                                    [](auto ch)
                                    {
                                        return (ch == '\n' ||
                                                ch == '\r'); 
                                    }),
                    sampleStr.end() );

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

    return 0;
}

Output:

This is Some String  some text  Another Text  The end

It removed all newline characters from the string.

Remove Newline characters from String using std::erase_if() in C++20

To remove all newline characters from a string, just pass the string and a lambda function to the std::erase() function as arguments. In lambda function check if character is either ‘\n’ or ‘\r’. For example,

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

int main()
{
    std::string sampleStr =
        "This is Some String \n\n\r\n some text \r\n Another Text \n\n The end";

    // Remove newline characters from string in C++
    std::erase_if( sampleStr,
                   [](auto ch)
                   {
                        return (ch == '\n' ||
                                ch == '\r'); 
                   });

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

    return 0;
}

Output:

This is Some String  some text  Another Text  The end

It removed all newline characters from the string.

Summary

We learned three different ways to remove all newline characters 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