Remove everything in string before a character – C++

This article will discuss how to delete everything before a character in a C++ string.

Suppose we have a string,

"The last-Warrior"

Now we want to delete all characters before the character ‘-‘, including the character ‘-‘. The final string should be like this,

"Warrior"

There are different ways to do this. Let’s discuss them one by one,

Remove everything before a character from a string using substr()

In C++, string class provides a function substr() to get a copy of sub-string from the calling string object,

Advertisements
string substr (size_t pos = 0, size_t len = npos) const;

Parameters:

  • pos :
    • Position of the first character to be copied as a substring.
    • As indexing starts from 0 in C++, so the index position of first character is 0. character is denoted by a value of 0 (not 1).
  • len :
    • Number of characters to be include in the substring from the starting position “pos”.
    • Default value is string::npos, which indicates all characters until the end of the string.

Returns:

  • It returns the sub-string as a newly constructed string object. This sub-string starts at character position pos and spans to len characters or till end of string if len is not provided.

We can use the substr() function to delete all characters before a specific character in a string. But for that, first, we need to look for the given character in the string using the string::find() function. The find() function accepts a character and returns the index position of the first occurrence of the given character in the string. If it does not exist in the string, then it returns string::npos.

If the given character exists in the string, then get all the characters from its index position till the end of string using the substr() function. For example,

#include <iostream>
#include <string>

int main()
{
    std::string sampleStr = "The last-Warrior";

    char ch = '-';

    // Get the position of first occurrence of character
    std::size_t pos = sampleStr.find(ch);

    // Check if index position is valid  
    if (pos != std::string::npos)
    {
        // Remove all characters before the given position 
        sampleStr = sampleStr.substr(pos+1);
    }

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

    return 0;
}

Output:

Warrior

It deleted all the characters before the given character, including the character itself.

Remove everything before a character from a 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

  • String from which we need to replace the characters.
  • The regex pattern is based on which sub-strings will be matched in the string.
  • 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 delete all characters before a given character in a string. For that, we need to pass these three arguments to regex_replace(),

  • String from which we need to delete the characters.
  • A regex pattern “(.)(-)(.)”, to match the whole string and segregate the matched string into three groups i.e.
    • All characters before ‘-‘
    • The character ‘-‘
    • All characters before ‘-‘
  • “$3” as the Replacement string. It will replace the contents of the string with the third group in the matched string i.e. characters after the ‘-‘.

For example,

#include <iostream>
#include <string>
#include <regex>

int main()
{
    std::string sampleStr = "The last-Warrior";

    // Regex pattern to select three groups i.e.
    // Characters before '-'
    // The character '-'
    // Characters after '-'
    std::regex pattern ("(.*)(-)(.*)");

    // Remove all characters before the given position
    sampleStr = std::regex_replace( sampleStr,
                                    pattern,
                                    "$3");

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


    return 0;
}

Output:

Warrior

It deleted all the characters before the given character, including the character itself.

If you don’t want to remove the delimiter character too i.e. ‘-‘. Then you can pass the “$2$3” as the replacement string. For example,

#include <iostream>
#include <string>
#include <regex>

int main()
{
    std::string sampleStr = "The last-Warrior";

    // Regex pattern to select three groups i.e.
    // Characters before '-'
    // The character '-'
    // Characters after '-'
    std::regex pattern ("(.*)(-)(.*)");

    // Remove all characters before the given position
    sampleStr = std::regex_replace( sampleStr,
                                    pattern,
                                    "$2$3");

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


    return 0;
}

Output:

-Warrior

It deleted only the characters before the given character.

Summary:

We learned two ways to delete all the characters from the string before a given character 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