Android Implements Sorting Chinese by Phonetic
- 2021-06-28 13:49:27
- OfStack
The requirement of this article is to sort a set of data by Chinese phonetic in a field and share it with you in Android to implement Chinese phonetic sorting method for your reference. The details are as follows:
1. Test test class:
PinyinComparator comparator = new PinyinComparator();
Collections.sort(strList, comparator);
There is data in strList, which can be any object, but to modify compare in PinyinComparator, I have String in Demo [].
2. PinyinComparator Sort Class:
public class PinyinComparator implements Comparator<Object> {
/**
* Compare two strings
*/
public int compare(Object o1, Object o2) {
String[] name1 = (String[]) o1;
String[] name2 = (String[]) o2;
String str1 = getPingYin(name1[0]);
String str2 = getPingYin(name2[0]);
int flag = str1.compareTo(str2);
return flag;
}
/**
* Convert Chinese into Pinyin in a string , Other characters unchanged
*
* @param inputString
* @return
*/
public String getPingYin(String inputString) {
HanyuPinyinOutputFormat format = new HanyuPinyinOutputFormat();
format.setCaseType(HanyuPinyinCaseType.LOWERCASE);
format.setToneType(HanyuPinyinToneType.WITHOUT_TONE);
format.setVCharType(HanyuPinyinVCharType.WITH_V);
char[] input = inputString.trim().toCharArray();// Converts a string to an array of characters
String output = "";
try {
for (int i = 0; i < input.length; i++) {
// \\u4E00 yes unicode Encoding to determine if it is Chinese
if (java.lang.Character.toString(input[i]).matches(
"[\\u4E00-\\u9FA5]+")) {
// Save the whole spelling of Chinese Pinyin to temp array
String[] temp = PinyinHelper.toHanyuPinyinStringArray(
input[i], format);
// Phonetic number 1 Pronunciation
output += temp[0];
}
// Convert uppercase letters to lowercase letters
else if (input[i] > 'A' && input[i] < 'Z') {
output += java.lang.Character.toString(input[i]);
output = output.toLowerCase();
}
output += java.lang.Character.toString(input[i]);
}
} catch (Exception e) {
Log.e("Exception", e.toString());
}
return output;
}
}
This is the whole content of this article, and I hope it will be helpful for everyone to learn.