Android provides a class for converting Chinese characters to pinyin. However, this class is under the contact app. The specific directory is the HanziToPinyin. java file of packages/providers/ContactsProvider/src/com/android/providers/contacts. If you want this tool class, you can directly copy it for use.
How to obtain a complete Chinese Character spell:
[Java]
Public String getFullPinYin (String source ){
If (! Arrays. asList (Collator. getAvailableLocales (). contains (Locale. CHINA )){
Return source;
}
ArrayList <Token> tokens = HanziToPinyin. getInstance (). get (source );
If (tokens = null | tokens. size () = 0 ){
Return source;
}
StringBuffer result = new StringBuffer ();
For (Token token: tokens ){
If (token. type = Token. PINYIN ){
Result.append(token.tar get );
} Else {
Result. append (token. source );
}
Return result. toString ();
}
To obtain a simplified Chinese character segment:
[Java] www.2cto.com
Public String getFirstPinYin (String source ){
If (! Arrays. asList (Collator. getAvailableLocales (). contains (Locale. CHINA )){
Return source;
}
ArrayList <Token> tokens = HanziToPinyin. getInstance (). get (source );
If (tokens = null | tokens. size () = 0 ){
Return source;
}
StringBuffer result = new StringBuffer ();
For (Token token: tokens ){
If (token. type = Token. PINYIN ){
Result.append(token.tar get. charAt (0 ));
} Else {
Result. append ("#");
}
Return result. toString ();
}
Example:
[Java] view plaincopyprint?
String str = "I am a Chinese ";
GetFullPinYin (str); // WOSHIZHONGGUOREN is returned.
GetFirstPinYin (str); // WSZGR is returned.
Author: fangchongbory