Get Chinese pinyin for Android

Source: Internet
Author: User
Tags collator

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

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.