C plus plus code to Extract/Replace String between two delimiters

This article shows the C plus plus (C++) code to extract/replace a sub-string between two delimiters or characters using find and substr functions.

Extract String between two delimiters

For example, if you want to extract the string between two delimiters “[” and “]” from Sri[nivas]an , then the CPP code will be

#include <iostream> 
using namespace std; 
  
int main() 
{ 
    // Take any string 
    string s1 = "Sri[nivas]an"; 
  
    // Find the position of first delimiter 
    int firstDelPos = s1.find("[");
    // Find the position of second delimiter
    int secondDelPos = s1.find("]");
    // Get the substring between two delimiters
    string strbetweenTwoDels = s1.substr(firstDelPos+1, secondDelPos-firstDelPos-1); 
  
    // prints the result 
    cout << "String between delimiters [ and ] is: " << strbetweenTwoDels; 
  
    return 0; 
} 
CPP output to extract a string between two delimiters
CPP code output to extract a string between two delimiters

Replace String between two delimiters

Below is the C plus plus code to replace string between two characters or delimiters within a string. Code replaces “nivasa” between delimiters “[” and “]” in “Sri[nivasa]n” with “vas”.

#include <iostream> 
using namespace std; 
  
int main() 
{ 
    // Take any string 
    string s1 = "Sri[nivasa]n"; 
    string strToReplace = "vas";
  
    // Find the position of first delimiter 
    int firstDelPos = s1.find("[");
    // Find the position of second delimiter
    int secondDelPos = s1.find("]");
    // Replace substring between two delimiters
    string strbetweenTwoDels = s1.replace(firstDelPos+1, secondDelPos-firstDelPos-1,strToReplace); 
  
    // prints the result 
    cout << "String after replacing the sub string between delimiters [ and ] is: " << strbetweenTwoDels; 
  
    return 0; 
} 
screenshot of result of replace string between delimiters or characters in c plus plus
result of replace string between delimiters or characters in c++

Check Extract string between two delimiters in Python

About the Author

SRINI S

A passionate blogger. Love to share solutions and best practices on wordpress hosting, issues and fixes, excel VBA macros and other apps

Leave a Reply

Your email address will not be published.