Extract maximum numeric value from a given string | Set 1 ( General approach ) | Java program for above implementation ; Utility method 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 ; Method 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 ; Driver method
class GFG { static 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 . charAt ( i ) == res . charAt ( i ) ) i ++ ; if ( curr_num . charAt ( i ) < res . charAt ( i ) ) return res ; else return curr_num ; } return len1 < len2 ? res : curr_num ; } static String extractMaximum ( String str ) { int n = str . length ( ) ; String curr_num = " " ; String res = " " ; for ( int i = 0 ; i < n ; i ++ ) { while ( i < n && str . charAt ( i ) == '0' ) i ++ ; while ( i < n && Character . isDigit ( str . charAt ( i ) ) ) { curr_num = curr_num + str . charAt ( i ) ; i ++ ; } if ( i == n ) break ; if ( curr_num . length ( ) > 0 ) i -- ; res = maximumNum ( curr_num , res ) ; curr_num = " " ; } if ( curr_num . length ( ) == 0 && res . length ( ) == 0 ) res = res + '0' ; return maximumNum ( curr_num , res ) ; } public static void main ( String [ ] args ) { String str = "100klh564abc365bg " ; System . out . println ( extractMaximum ( str ) ) ; } }