Sort by the Chinese character string according to Pinyin

xiaoxiao2021-03-06  96

Today, Shuimu found that someone asked how to sort the Chinese character string, checked a document, found that Java default sorted by the size of each Unicode character. Then I find (if there is no Google, what will the world going?) There is a Java.Text.collator class, but some people say that this class is useless, like the default sort effect, to write a class to generate Java with C # program. If this is true, then do you learn Java? So I changed the Test.java's Test.java, and I tried with the specified locale and not specified Locale. The result is OK: import java.util. *;

Import java.text. *;

Public class test2 {

Public static void testdefault () {

String [] arr = {"Zhang San", "Li Si", "Wang Wu", "Liu Liu"}

Arrays.sort (Arr);

For (int i = 0; i

System.out.println (Arr [i]);

SYSTEM.OUT.PRINTLN ();

}

Public static void testchinalocale () {

// Comparator CMP = (rulebasedcollator) java.text.collator.getinstance (java.util.locale.china); // Try Testing Various Locales

Comparator cmp = collator.getinstance (java.util.locale.china);

String [] arr = {"Zhang San", "Li Si", "Wang Wu", "Liu Liu"}

Arrays.Sort (Arr, CMP);

For (int i = 0; i

System.out.println (Arr [i]);

SYSTEM.OUT.PRINTLN ();

}

Public static void testdefaultlocale () {

// Comparator CMP = (rulebasedcollator) java.text.collator.getinstance (java.util.locale.china); // Try Testing Various Locales

Comparator cmp = collator.getinstance ();

String [] arr = {"Zhang San", "Li Si", "Wang Wu", "Liu Liu"}

Arrays.Sort (Arr, CMP);

For (int i = 0; i

System.out.println (Arr [i]);

SYSTEM.OUT.PRINTLN ();

}

Public static void main (string args []) {

TestDefault ();

TestchChinaAlocale ();

TestDefaultlocale ();

}

}

Output results:

Liu Liu

Zhang San

Li Si

Wang Wu

Li Si

Liu Liu

Wang Wu

Zhang San

Li Si

Liu Liu

Wang Wu

Zhang San

It seems that Java is not so bad. As for the old brother, it is estimated that there is a problem with the default Locale. Below is a test code in the string of Google on Java.net: import java.util. *; Import java.us *; import java.text. *; Public class charsort item company {java .text.RuleBasedCollator collator; // you can set your rules for the instance "collator" CharSort () {collator = (RuleBasedCollator) java.text.Collator.getInstance (java.util.Locale.CHINA); // try testing various Locales} public void dosort (string str) throws java.io iexception {java.text.collationKey [] keys = new java.text.collationKey [str.length ()]; for (int i = 0; i

转载请注明原文地址:https://www.9cbs.com/read-105619.html

New Post(0)