我有一个字符串数组:
void populateStringArray()
{
toppings = new String[20];
toppings[0] = "Cheese12";
toppings[1] = "Pepperoni1234";
toppings[2] = "Black Olives1";
// ...
我想返回数字字符最少的那个。
有人可以提出实现这一目标的逻辑吗?
我有一个字符串数组:
void populateStringArray()
{
toppings = new String[20];
toppings[0] = "Cheese12";
toppings[1] = "Pepperoni1234";
toppings[2] = "Black Olives1";
// ...
我想返回数字字符最少的那个。
有人可以提出实现这一目标的逻辑吗?
如果使用Guava是一个选项,你可以这样做:
int digitChars = CharMatcher.DIGIT.countIn(yourString)
str
您可以计算字符串中的位数
str.length() - str.replaceAll("\\d", "").length()
像馅饼一样简单。
现在你所要做的就是遍历你的数组并找到最小toppings
的字符串s
。str.length() - str.replaceAll("\\d", "").length()
您可以遍历字符并用于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
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
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;
}
您可以使用正则表达式查找字符串中的所有数字并计算位数:
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)");