在java中测试给定字符串中所有包含的数字都是升序的有效方法是什么?
示例字符串可能是
String ascending = "Welc2ome T3o Co3mp67uter W99orld";
String notAscending = "Welc8ome T3o Co3mp67uter W99orld";
避免使用String.split
或Integer.parseInt
,因为它效率不高。
如果应该支持国际数字和unicode字符,以下可能是一个解决方案。
public static boolean isNumericValuesAscending(String s) {
int max = -1;
for (int i = 0; i< s.length(); i++) {
char current = s.charAt(i);
boolean isDigit = Character.isDigit(current);
if (isDigit) {
int currentNumericValue = Character.getNumericValue(current);
if (max <= currentNumericValue) {
max = currentNumericValue;
} else {
return false;
}
}
}
return true;
}
如果If条件max <= currentNumericValue
更改为max < currentNumericValue
,则不允许T3o Co3
和W99orld
等重复数值。
它可以使用Java Streams+AtomicInteger
以更简洁的方式实现,以跟踪前一个数字:
public static boolean ascendingDigits(String s) {
AtomicInteger prev = new AtomicInteger('0');
return s.chars()
.mapToObj(c -> (char)c) // Stream of Character
.filter(Character::isDigit) // filter digits including Unicode ranges
.allMatch(c -> prev.getAndSet(c) <= c); // compare previous digit to current and update the previous one
}
测试:
String asc = "Welc2ome T3o Co3mp67uter W89orlduFF10 uFF15 uFF17"; // using fullwidth digits
System.out.println(asc);
System.out.println(ascendingDigits(asc));
String notAscending = "Welc8ome T3o Co3mp67uter W99orld";
System.out.println(ascendingDigits(notAscending));
输出:
Welc2ome T3o Co3mp67uter W89orld0 5 7
true
false