Get string before a character in C++

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

To get a substring before a specific character in a string, first we need to check if the given character exists in the string or not. If string contains the specified character, then we need to fetch its index position, and then we can use the substr() function of std::string to fetch a substring from index 0, till the index position of the given character in string. We have created a separate function for this,

// Get String before a character 
// from the specified string
std::string getSubString(
            const std::string& strValue,
            const char& ch)
{
    std::string subString = "";

    // Get index position of the character
    std::size_t endPos = strValue.find(ch);

    // Check if the character exists in string
    if( endPos != std::string::npos)
    {
        // Get substring from before the specifed character
        subString = strValue.substr(0, endPos);
    }

    return subString;

}

It will accept a string and a character as arguments, and returns a part of string i.e. before the specified character in the string.

It will use string::find() function to fetch the index position of the given character. If the given character exists in the string, then it will use the string::substr() function of string to fetch a substring from index position zero till the index position of the specified character.

In the below example, we will fetch a substring from “The latest text from press” i.e. from first character till character ‘x’ in the string.

Let’s see the complete example,

#include <iostream>
#include <string>
#include <algorithm>

// Get String before a character
// from the specified string
std::string getSubString(
            const std::string& strValue,
            const char& ch)
{
    std::string subString = "";

    // Get index position of the character
    std::size_t endPos = strValue.find(ch);

    // Check if the character exists in string
    if( endPos != std::string::npos)
    {
        // Get substring from before the specifed character
        subString = strValue.substr(0, endPos);
    }

    return subString;

}

int main()
{
    std::string strValue = "The latest text from press";

    // Get substring before 'x'
    std::string subString = getSubString(strValue, 'x');

    std::cout << subString << std::endl;
    return 0;
}

Output :

The latest te

Summary

Today we learned about several ways to get string before 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