Get String after a character in C++

This tutorial will discuss about a unique way to get string after a character in C++.

To get a substring from a string, after a specific character, first we need to check if the string contains the specified character or not. If yes, then we need to fetch the index position of its first occurrence. Once we have the index position then we can fetch the substring from that index position till the end of the string.

To fetch the index position of a specific character we can use the std::string::find() function. Whereas, to fetch a substring from a specific index position till the end of the string, we can use the std::strng::substr() function.

In the below example, we have a string “This is a :test string”, and we will fetch a part of string i.e. from the first occurrence of character ‘:’, till the end of string.

Let’s see the complete example,

#include <iostream>
#include <string>

int main()
{
    std::string strValue = "This is a :test string";

    char ch = ':';

    // Find the position of specified character in string
    std::size_t pos = strValue.find(ch);

    // Check if position is valid
    if (pos != std::string::npos)
    {
        // Fetch substring from the spcified character onwards
        std::string subString = strValue.substr(pos + 1);

        std::cout<<"Sub String after the character is: \""<< subString << "\" \n";
    }
    else
    {
        std::cout<<"Given character does not exists in string \n";
    }
    return 0;
}

Output :

Sub String after the character is: "test string"

Summary

Today we learned about several ways to get string after a character in C++. Thanks.

Leave a Comment

Your email address will not be published. Required fields are marked *

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

Scroll to Top