Extract substrings between any pair of delimiters | Java 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
import java . util . * ; class GFG { static void printSubsInDelimeters ( String str ) { Stack < Integer > dels = new Stack < Integer > ( ) ; for ( int i = 0 ; i < str . length ( ) ; i ++ ) { if ( str . charAt ( i ) == ' [ ' ) { dels . add ( i ) ; } else if ( str . charAt ( i ) == ' ] ' && ! dels . isEmpty ( ) ) { int pos = dels . peek ( ) ; dels . pop ( ) ; int len = i - 1 - pos ; String ans = str . substring ( pos + 1 , pos + 1 + len ) ; System . out . print ( ans + "NEW_LINE"); } } } public static void main ( String [ ] args ) { String str = " [ This ▁ is ▁ first ] ▁ ignored ▁ text ▁ [ This ▁ is ▁ second ] " ; printSubsInDelimeters ( str ) ; } }