Java 中的自然排序字符串比较
人类所理解的“自然”排序顺序是根据字符串的数值和按字母顺序排列的组件。这与默认的字典顺序不同,默认的字典顺序优先考虑字符顺序。
在 Java 中,没有专门为自然排序顺序设计的内置函数。但是,您可以使用以下外部实现来实现此行为:
<code class="java">// NaturalOrderComparator.java // License: Cougaar Open Source License import java.util.Comparator; public class NaturalOrderComparator implements Comparator<String> { @Override public int compare(String s1, String s2) { // Split strings into tokens String[] s1Tokens = s1.split("(?<=\D)(?=\d)|(?<=\d)(?=\D)"); String[] s2Tokens = s2.split("(?<=\D)(?=\d)|(?<=\d)(?=\D)"); // Compare tokens one by one int i = 0; while (i < Math.min(s1Tokens.length, s2Tokens.length)) { try { int n1 = Integer.parseInt(s1Tokens[i]); int n2 = Integer.parseInt(s2Tokens[i]); // Numerical comparison if (n1 != n2) { return n1 - n2; } } catch (NumberFormatException e) { // Alphabetical comparison int comparison = s1Tokens[i].compareTo(s2Tokens[i]); if (comparison != 0) { return comparison; } } i++; } // If all tokens are equal, compare lengths if (s1Tokens.length != s2Tokens.length) { return s1Tokens.length - s2Tokens.length; } // Strings are identical return 0; } }</code>
以上是如何用Java实现自然排序字符串比较?的详细内容。更多信息请关注PHP中文网其他相关文章!