Get string between quotes in C++

This tutorial will discuss about a unique way to get string between quotes in C++.

To get the substring between two quotes, fetch the index positions of first two quotes in string, and then get the substring between these two index positions. We have created a function to fetch the substring between two quotes in a string,

// Get substring between two quotes
std::string GetSubString(const std::string& strValue)
{
    std::string str = "";
    // Get index position of first quote in string
    size_t pos1 = strValue.find("\"");
    // Check if index is valid
    if(pos1 != std::string::npos)
    {
        // Get index position of second quote in string
        size_t pos2 = strValue.find("\"", pos1+1);
        // Check if index is valid
        if(pos2 != std::string::npos)
        {
            // Get substring between index positions of two quotes
            str = strValue.substr(pos1 + 1, pos2 - pos1 - 1);
        }
    }
    return str;
}

It accepts a string as an argument, and then looks for the index of first quote in the string using the string::find() function. Then it looks for the index position of second quote in the string using std::string::find() function. But this time, it searches after the index of first quote, this way it will get the index of second quote. If both the indices are valid, then use the string::substr() function to fetch the substring between these two index positions i.e. between the quotes.

Let’s see the complete example,

#include <iostream>
#include <string>

// Get substring between two quotes
std::string GetSubString(const std::string& strValue)
{
    std::string str = "";
    // Get index position of first quote in string
    size_t pos1 = strValue.find("\"");
    // Check if index is valid
    if(pos1 != std::string::npos)
    {
        // Get index position of second quote in string
        size_t pos2 = strValue.find("\"", pos1+1);
        // Check if index is valid
        if(pos2 != std::string::npos)
        {
            // Get substring between index positions of two quotes
            str = strValue.substr(pos1 + 1, pos2 - pos1 - 1);
        }
    }
    return str;
}

int main()
{
    std::string strValue = "This is a \"special\" text";

    // Get substring between two quotes
    std::string subStrng =  GetSubString(strValue);

    std::cout << subStrng << std::endl;

    return 0;
}

Output :

special

Summary

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