Extract substrings between any pair of delimiters | C ++ Program to implement the above approach ; Function to print strings present between any pair of delimeters ; Stores the indices of ; If opening delimeter is encountered ; If closing delimeter is encountered ; Extract the position of opening delimeter ; Length of substring ; Extract the substring ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; void printSubsInDelimeters ( string str ) { stack < int > dels ; for ( int i = 0 ; i < str . size ( ) ; i ++ ) { if ( str [ i ] == ' [ ' ) { dels . push ( i ) ; } else if ( str [ i ] == ' ] ' && ! dels . empty ( ) ) { int pos = dels . top ( ) ; dels . pop ( ) ; int len = i - 1 - pos ; string ans = str . substr ( pos + 1 , len ) ; cout << ans << endl ; } } } int main ( ) { string str = " [ This ▁ is ▁ first ] ▁ ignored ▁ text ▁ [ This ▁ is ▁ second ] " ; printSubsInDelimeters ( str ) ; return 0 ; }