Android 拼音轉漢字的第三方處理

2021-07-29 09:44:35 字數 1695 閱讀 2763

在我們的開發中,有時會有這樣的需求,就是聯絡人列表按照拼音順序排列(如通訊錄)。於是,我也在網上搜到了許多這類的文章,就兩種最常見的做法在此進行簡單的比較和分析

優點:使用簡單,實用性好

缺點:需要依賴第三方jar包

package com.afei.indexlistview;

import net.sourceforge.pinyin4j.pinyinhelper;

import net.sourceforge.pinyin4j.format.hanyupinyincasetype;

import net.sourceforge.pinyin4j.format.hanyupinyinoutputformat;

import net.sourceforge.pinyin4j.format.hanyupinyintonetype;

/** * 漢字轉換位漢語拼音,英文本元不變

*/public class cn2spell catch (exception e)

} else

}return sb.tostring();

}/**

* 獲取漢字字串的第乙個字母

*/public static string getpinyinfirstletter(string str) else

return sb.tostring();

}/**

* 獲取漢字字串的漢語拼音,英文本元不變

*/public static string getpinyin(string chines) catch (exception e)

} else

}return sb.tostring();

}}

優點:零依賴,只有乙個class,使用簡單

缺點:只支援常見的一級漢字,對於一些不常見的漢字(亳bo)則無法正確獲取拼音

(中文編碼中一級漢字是按拼音排序的,容易對映。而二級漢字是按筆畫部首排序的)

public class cn2spell ;

public static string pystr = new string ;

private stringbuilder buffer;

private static cn2spell cn2spell= new cn2spell ();

public static cn2spell getinstance()

// 漢字轉成ascii碼

private int getchsascii(string chs)

if (bytes.length == 1)

if (bytes.length == 2)

} catch (exception e)

return asc;

}// 單字解析

public string convert(string str) else }}

return result;

}// 片語解析

public string getselling(string chs)

} else

}return buffer.tostring();

}}

其實,無論是使用哪種方法,我發現都是沒有去處理多音字的情況(畢竟這個真不好寫),不過基本需求都可以滿足啦

漢字轉拼音

region 漢字轉拼音 漢字轉拼音類 用法 crazycoderpinyin.covent 漢字 長度 using system.text.regularexpressions build date 20030610 public class crazycoderpinyin 定義陣列 priva...

漢字轉拼音

工具pinyin4j 2.5.0.jar 整理了3個方法,1.漢字轉拼音 2.返回中文姓 中文名 英文姓 last name 英文名 first name 3.返回首字母 public class pinyin4jdemo char hanzi word.tochararray string t2 ...

漢字轉拼音

ios mac os x 漢字轉拼音 網路流行的漢字轉拼音方案是帶乙個拼音碼表,速度快。其實core foundation也提供了一種方案,而且還帶聲調!nsmutablestring ms nsmutablestring alloc initwithstring 我是中國人 if cfstring...