Conversion of Chinese characters to PinYin in Java

Source: Internet
Author: User

Need to download pinyin4j: http://pinyin4j.sourceforge.net/

 

Code

Package utils;

Import net. SourceForge. pinyin4j .*;
Import net. SourceForge. pinyin4j. format .*;
Import net. SourceForge. pinyin4j. format. Exception .*;

Public class pinyin {
/**
* Convert Chinese characters to full spelling
*
* @ Param SRC
* @ Return
*/
Public static string getpingyin (string SRC ){
Char [] T1 = NULL;
T1 = SRC. tochararray ();
String [] T2 = new string [t1.length];
Hanyupinyinoutputformat T3 = new hanyupinyinoutputformat ();
T3.setcasetype (hanyupinyincasetype. lowercase );
T3.settonetype (hanyupinyintonetype. without_tone );
T3.setvchartype (hanyupinyinvchartype. with_v );
String t4 = "";
Int T0 = t1.length;
Try {
For (INT I = 0; I <t0; I ++ ){
// Determine whether it is a Chinese character
If (Java. Lang. character. tostring (T1 [I]). Matches (
"[\ U4e00-\ u9fa5] + ")){
T2 = pinyinhelper. tohanyupinyinstringarray (T1 [I], T3 );
T4 + = t2 [0];
} Else
T4 + = java. Lang. character. tostring (T1 [I]);
}
// System. Out. println (T4 );
Return T4;
} Catch (badhanyupinyinoutputformatcombination E1 ){
E1.printstacktrace ();
}
Return T4;
}

/**
* Returns the first letter of a Chinese character.
*
* @ Param Str
* @ Return
*/
Public static string getpinyinheadchar (string Str ){

String convert = "";
For (Int J = 0; j <Str. Length (); j ++ ){
Char word = Str. charat (j );
String [] pinyinarray = pinyinhelper. tohanyupinyinstringarray (Word );
If (pinyinarray! = NULL ){
Convert + = pinyinarray [0]. charat (0 );
} Else {
Convert + = word;
}
}
Return convert;
}

Public static void main (string [] ARGs ){
String cnstr = "People's Republic of China ";
System. Out. println (getpingyin (cnstr ));
System. Out. println (getpinyinheadchar (cnstr ));
}
}

 

 

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.