Android實現中文按拼音排序方法
更新時間:2016年03月14日 16:19:02 作者:gqdy365
這篇文章主要為大家詳細介紹了Android實現中文按拼音排序方法,很實用,感興趣的小伙伴們可以參考一下
本文的需求是將一組數據按某一字段中文拼音排序,分享給大家Android實現中文按拼音排序方法,供大家參考,具體內容如下
1、Test測試類:
PinyinComparator comparator = new PinyinComparator();
Collections.sort(strList, comparator);
其中strList中放置了數據,可以是任何對象,但要對PinyinComparator中的compare進行對應的修改,我Demo中為String[]。
2、PinyinComparator排序類:
public class PinyinComparator implements Comparator<Object> {
/**
* 比較兩個字符串
*/
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;
}
/**
* 將字符串中的中文轉化為拼音,其他字符不變
*
* @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();// 把字符串轉化成字符數組
String output = "";
try {
for (int i = 0; i < input.length; i++) {
// \\u4E00是unicode編碼,判斷是不是中文
if (java.lang.Character.toString(input[i]).matches(
"[\\u4E00-\\u9FA5]+")) {
// 將漢語拼音的全拼存到temp數組
String[] temp = PinyinHelper.toHanyuPinyinStringArray(
input[i], format);
// 取拼音的第一個讀音
output += temp[0];
}
// 大寫字母轉化成小寫字母
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;
}
}
以上就是本文的全部內容,希望對大家的學習有所幫助。
您可能感興趣的文章:
- android實現漢字轉拼音功能 帶多音字識別
- Android實現ListView的A-Z字母排序和過濾搜索功能 實現漢字轉成拼音
- android仿微信通訊錄搜索示例(匹配拼音,字母,索引位置)
- Android開發(fā)實現的IntentUtil跳轉多功能工具類【包含視頻、音頻、圖片、攝像頭等操作功能】
- android實用工具類分享(獲取內存/檢查網絡/屏幕高度/手機分辨率)
- android開發(fā)教程之實現toast工具類
- 19個Android常用工具類匯總
- android 一些工具類匯總
- Android7.0 工具類:DiffUtil詳解
- 非常實用的Android圖片工具類
- Android開發(fā)之拼音轉換工具類PinyinUtils示例
相關文章
Android studio虛擬機在啟動界面和桌面出現畫面模糊花屏問題的解決方法
這篇文章主要介紹了解決Android studio虛擬機在啟動界面和桌面出現畫面模糊花屏問題,本文通過圖文并茂的形式給大家介紹的非常詳細,需要的朋友可以參考下2020-03-03

