使用最少数量的数字字符验证数组

时间:2012-10-29 16:00:32

标签: java

我有一个字符串数组:

void populateStringArray()
{
toppings = new String[20];

toppings[0] = "Cheese12";
toppings[1] = "Pepperoni1234";
toppings[2] = "Black Olives1";
// ...

我想要返回一个字符数最少的字符。

有人可以提出实现这个目标的逻辑吗?

6 个答案:

答案 0 :(得分:2)

如果使用Guava是一个选项,您可以这样做:

int digitChars = CharMatcher.DIGIT.countIn(yourString)

答案 1 :(得分:2)

您可以使用

计算字符串str中的位数
str.length() - str.replaceAll("\\d", "").length()

简单如馅饼。

现在你所要做的就是遍历数组toppings并找到s最少的字符串str.length() - str.replaceAll("\\d", "").length()

答案 2 :(得分:1)

您可以循环遍历字符并使用Character.isDigit()计算字符串中的数字。

   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);

输出:

2 

答案 3 :(得分:1)

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

答案 4 :(得分:0)

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;
}

答案 5 :(得分:0)

您可以使用正则表达式查找字符串中的所有数字并计算位数:

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;
}

现在,您可以遍历数组并找到数字量最少的数组:

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