Remove everything in string after a character – C++

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

Suppose we have a string,

"The last-Warrior"

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

The last

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

Remove everything after 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 after 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 index position 0 till the index position of the given character using 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 after the given position 
        sampleStr = sampleStr.substr(0, pos);
    }

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

    return 0;
}

Output:

The last

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

Remove everything after 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 after 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 after ‘-‘
  • “$1” as the Replacement string. It will replace the contents of the string with the first group in the matched string i.e. characters before 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.
    // All characters before '-'
    // The character '-'
    // All characters after '-'
    std::regex pattern ("(.*)(-)(.*)");

    // Replace all characters in string with group 1
    sampleStr = std::regex_replace( sampleStr,
                                    pattern,
                                    "$1");

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

    return 0;
}

Output:

The last

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

If you don’t want to remove the delimiter character i.e. ‘-‘. Then you can pass the “$1$2” 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.
    // All characters before '-'
    // The character '-'
    // All characters after '-'
    std::regex pattern ("(.*)(-)(.*)");

    // Replace all characters in string with group 1
    sampleStr = std::regex_replace( sampleStr,
                                    pattern,
                                    "$1$2");

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

    return 0;
}

Output:

The last-

It deleted only the characters after the given character.

Summary:

We learned two ways to delete all the characters from the string after 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