This tutorial will discuss about unique ways to get string between two characters in C++.
Suppose we have a string, and we want to get a substring from this main string. We will have two characters, and we need to fetch a substring between these two specific characters from the main string. For example,
- Main string is –> “The latest text from press”
- Two characters are, ‘l’ and ‘x’
The substring between these two characters will be “atest te”.
To do that, first we need to check if both the characters exists in the string or not. If yes, then we need to fetch the endex positions of these two characters using std::string::find()
function. Once we have the index positions of these two characters in string, then we can easily fetch the substring between these two index positions using the string::substr()
function. For that we need to pass the index position of first character as the first argument in substr()
function, and number of characters that need to be fetched as second argument in the substr()
function. The number of characters that need to be fetched is ‘endIndex – startIndex -1’. This way, substr()
will return a substring between the two specific characters.
Let’s see the complete example,
Pointers in C/C++ [Full Course]
#include <iostream> #include <string> #include <algorithm> // Get String between two specific characters std::string getSubString( const std::string& strValue, const char& startChar, const char& endChar) { std::string subString = ""; // Get index position of first character std::size_t startPos = strValue.find(startChar); // Get index position of second character std::size_t endPos = strValue.find(endChar); // Check if both the characters exists in string if( startPos != std::string::npos && endPos != std::string::npos) { // Get substring from start to end character subString = strValue.substr(startPos + 1, endPos - startPos - 1); } return subString; } int main() { std::string strValue = "The latest text from press"; // Get substring between character 'l' and 'x' std::string subString = getSubString(strValue, 'l', 'x'); std::cout << subString << std::endl; return 0; }
Output :
atest te
Summary
Today we learned about several ways to get string between two characters in C++. Thanks.