Extract maximum numeric value from a given string | Set 1 ( General approach ) | C ++ program for above implementation ; Utility function to find maximum string ; If both having equal lengths ; Reach first unmatched character / value ; Return string with maximum value ; If different lengths return string with maximum length ; Function to extract the maximum value ; Start traversing the string ; Ignore leading zeroes ; Store numeric value into a string ; Update maximum string ; To handle the case if there is only 0 numeric value ; Return maximum string ; Drivers program
#include <bits/stdc++.h> NEW_LINE using namespace std ; string maximumNum ( string curr_num , string res ) { int len1 = curr_num . length ( ) ; int len2 = res . length ( ) ; if ( len1 == len2 ) { int i = 0 ; while ( curr_num [ i ] == res [ i ] ) i ++ ; if ( curr_num [ i ] < res [ i ] ) return res ; else return curr_num ; } return len1 < len2 ? res : curr_num ; } string extractMaximum ( string str ) { int n = str . length ( ) ; string curr_num = " " ; string res ; for ( int i = 0 ; i < n ; i ++ ) { while ( i < n && str [ i ] == '0' ) i ++ ; while ( i < n && str [ i ] >= '0' && str [ i ] <= '9' ) { curr_num = curr_num + str [ i ] ; i ++ ; } if ( i == n ) break ; if ( curr_num . size ( ) > 0 ) i -- ; res = maximumNum ( curr_num , res ) ; curr_num = " " ; } if ( curr_num . size ( ) == 0 && res . size ( ) == 0 ) res = res + '0' ; return maximumNum ( curr_num , res ) ; } int main ( ) { string str = "100klh564abc365bg " ; cout << extractMaximum ( str ) << endl ; return 0 ; }