Repeat substrings of the given String required number of times | Java implementation of the approach ; Function that returns true if the passed character is a digit ; Function to return the next index of a non - digit character in the string starting at the index i ( returns - 1 if no such index is found ) ; If the character at index i is a digit then skip to the next character ; If no such index was found ; Function to append str the given number of times to the StringBuilder ; Function to return the string after performing the given operations ; To build the resultant string ; Index of the first non - digit character in the string ; While there are substrings that do not consist of digits ; Find the ending of the substring ; Starting index of the number ; If no digit appears after the current substring ; Find the index at which the current number ends ; Parse the number from the substring ; Repeat the current substring required number of times ; Find the next non - digit character index ; Return the resultant string ; Driver code
class GFG { static boolean isDigit ( char ch ) { if ( ch >= '0' && ch <= '9' ) return true ; return false ; } static int nextNonDigit ( String str , int i ) { while ( i < str . length ( ) && isDigit ( str . charAt ( i ) ) ) { i ++ ; } if ( i >= str . length ( ) ) return - 1 ; return i ; } static void appendRepeated ( StringBuilder sb , String str , int times ) { for ( int i = 0 ; i < times ; i ++ ) sb . append ( str ) ; } static String findString ( String str , int n ) { StringBuilder sb = new StringBuilder ( " " ) ; int startStr = nextNonDigit ( str , 0 ) ; while ( startStr != - 1 ) { int endStr = startStr ; while ( ( endStr + 1 ) < n && ! isDigit ( str . charAt ( endStr + 1 ) ) ) { endStr ++ ; } int startNum = endStr + 1 ; if ( startNum == - 1 ) break ; int endNum = startNum ; while ( ( endNum + 1 ) < n && isDigit ( str . charAt ( endNum + 1 ) ) ) { endNum ++ ; } int num = Integer . parseInt ( str . substring ( startNum , endNum + 1 ) ) ; appendRepeated ( sb , str . substring ( startStr , endStr + 1 ) , num ) ; startStr = nextNonDigit ( str , endStr + 1 ) ; } return sb . toString ( ) ; } public static void main ( String [ ] args ) { String str = " g1ee1ks1for1g1e2ks1" ; int n = str . length ( ) ; System . out . println ( findString ( str , n ) ) ; } }