Validating the array with the least number of numeric characters

I have an array of strings:

void populateStringArray() { toppings = new String[20]; toppings[0] = "Cheese12"; toppings[1] = "Pepperoni1234"; toppings[2] = "Black Olives1"; // ... 

And I want to return the character with the smallest numeric characters.

Can anyone suggest a logic to achieve this?

+4
source share
6 answers

You can iterate over characters and use Character.isDigit() to count the numbers in a string.

  String str = "Cheese12"; int count = 0; for (int i = 0; i < str.length(); i++) { if (Character.isDigit(str.charAt(i))) { count++; } } System.out.println(count); 

Output:

 2 
+1
source

If using Guava , you can simply do this:

 int digitChars = CharMatcher.DIGIT.countIn(yourString) 
+2
source

You can count the number of digits in a str string with

 str.length() - str.replaceAll("\\d", "").length() 

Just like a pie.

Now all you have to do is loop over your toppings array and find the string s for which str.length() - str.replaceAll("\\d", "").length() less.

+2
source
 Pattern p = Pattern.compile("-?\\d+"); //regex pattern to find integers on a string int index = 0; int test; int lowest = Integer.MAX_VALUE; for (int i : toppings.size()-1){ Matcher m = p.matcher(toppings[i]); if (m.find()) { //assuming only one number to find test = Integer.parseInt(m.group()); if (test < lowest){ lowest = test; index = i; } } } return patterns[index]; //in case of tie the lowest index wins 
+1
source
 String leastChar(){ int leastChar=Integer.MAX_VALUE; String leastTopping=null; int eachToppingTemp=0; for (String topping:toppings){ if (topping==null) continue; eachToppingTemp= Integer.MAX_VALUE; for (char eachChar:topping.toCharArray()){ if (Character.isDigit(eachChar)){ eachToppingTemp++; } } if (eachToppingTemp<leastChar){ leastChar=eachToppingTemp; leastTopping=topping; } } System.out.println("Lowest char topping : "+leastTopping); return leastTopping; } 
0
source

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)"); 
0
source

Source: https://habr.com/ru/post/1442794/


All Articles