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; }
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; }