You can find all the digits in your string using a regular expression and count the number of digits:
public int getNumberOfDigitsInString(String input) { Pattern pattern = Pattern.compile("\\d+"); Matcher matcher = pattern.matcher(input); int count = 0; while (matcher.find()) count += matcher.group().length(); return count; }
Now you can just iterate over your array and find the one that has the least number of digits:
int lowestN = Integer.MAX_VALUE; String finalString = ""; for (String str:toppings) { int currentN = getNumberOfDigitsInString(str); if (lowestN > currentN) { finalStr = str; lowestN = currentN; } } System.out.println("Result: " + finalStr + " (has " + lowestN + " digits in it)");
source share