Repeat substrings of the given String required number of times | C ++ 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 ifno 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
#include <bits/stdc++.h> NEW_LINE using namespace std ; bool isDigit ( char ch ) { if ( ch >= '0' && ch <= '9' ) return true ; return false ; } int nextNonDigit ( string str , int i ) { while ( i < str . length ( ) && isDigit ( str [ i ] ) ) { i ++ ; } if ( i >= str . length ( ) ) return -1 ; return i ; } void appendRepeated ( string & sb , string str , int times ) { for ( int i = 0 ; i < times ; i ++ ) sb . append ( str ) ; } string findString ( string str , int n ) { string sb = " " ; int startStr = nextNonDigit ( str , 0 ) ; while ( startStr != -1 ) { int endStr = startStr ; while ( ( endStr + 1 ) < n && ! isDigit ( str [ endStr + 1 ] ) ) { endStr ++ ; } int startNum = endStr + 1 ; if ( startNum == -1 ) break ; int endNum = startNum ; while ( ( endNum + 1 ) < n && isDigit ( str [ endNum + 1 ] ) ) { endNum ++ ; } int num = str [ startNum ] - '0' ; appendRepeated ( sb , str . substr ( startStr , endStr + 1 - startStr ) , num ) ; startStr = nextNonDigit ( str , endStr + 1 ) ; } return sb ; } int main ( ) { string str = " g1ee1ks1for1g1e2ks1" ; int n = str . length ( ) ; cout << findString ( str , n ) << endl ; return 0 ; }