Write a program to extract maximum numeric value from a given string. In java | Sololearn: Learn to code for FREE!
Neuer Kurs! Jeder Programmierer sollte generative KI lernen!
Kostenlose Lektion ausprobieren
0

Write a program to extract maximum numeric value from a given string. In java

For example: this is ÔÇťThere is 60 students in csed section, 40 in cseb, and 55 in cseaÔÇŁ input string and output is 60.

16th Nov 2020, 1:02 PM
Ajit Kumar
1 Antwort
+ 1
The trickiest part of the question is the first step. You need to get the numbers out of the string. "number" can mean integer or double. The question doesn't make it completely clear if you want integers or doubles so I'm giving both below. Also, the question doesn't clearly say if negatives should be included so the below code includes "-" when scanning the string for numbers. The following should work if you just want integers. private static int[] getIntegers(String s) { s = s.replaceAll("[^\\-0-9]+", " "); String[] integerStrings = s.trim().split(" "); int[] result = new int[integerStrings.length]; int i = 0; for (String number: integerStrings) { result[i] = Integer.parseInt(number); i++; } return result; } This should work if you want doubles. private static double[] getDoubles(String s) { s = s.replaceAll("[^\\-\\.0-9]+", " "); String[] doubleStrings = s.trim().split(" "); double[] result = new double[doubleStrings.length]; int i = 0; for (String number: doubleStrings) { result[i] = Double.parseDouble(number); i++; } return result; } The above isn't completely perfect but should help you anyway. Both methods include all occurrences of "-" so it is possible to get parsing errors if other words include "-". If you don't care about negative numbers, remove the \\- from the regular expressions. Removing it will mean that all "-" characters are assumed to not be part of a number and it'll fix for the rare case that "-" is not attached to a number. Getting maximum number from an array of numbers should be simple enough for you to do.
16th Nov 2020, 9:21 PM
Josh Greig
Josh Greig - avatar