public class PinYin {
private static int BEGIN = 45217 ;
private static int END = 63486 ;
private static char [ ] charArray = { '啊' , '芭' , '擦' , '搭' , '蛾' , '发' , '噶' ,
'哈' , '击' , '喀' , '垃' , '妈' , '拿' ,
'哦' , '啪' , '期' , '然' , '撒' , '塌' ,
'挖' , '昔' , '压' , '匝' , } ;
private static int [ ] table = new int [ 24 ] ;
private static char [ ] initialArray = { 'a' , 'b' , 'c' , 'd' , 'e' , 'f' , 'g' ,
'h' , 'j' , 'k' , 'l' , 'm' , 'n' ,
'o' , 'p' , 'q' , 'r' , 's' , 't' ,
'w' , 'x' , 'y' , 'z' , } ;
static {
for ( int i = 0 ; i < 23 ; i++ ) {
table[ i] = getCharValue ( charArray[ i] ) ;
}
table[ 23 ] = END;
}
private static char char2Initial ( char ch) {
if ( ch >= 'a' && ch <= 'z' ) {
return ch;
}
if ( ch >= 'A' && ch <= 'Z' ) {
return ( char ) ( ch + ( 'a' - 'A' ) ) ;
}
int gb = getCharValue ( ch) ;
if ( ( gb < BEGIN) || ( gb > END) )
{
return ch;
}
int i;
for ( i = 0 ; i < 23 ; i++ ) {
if ( ( gb >= table[ i] ) && ( gb < table[ i + 1 ] ) ) {
break ;
}
}
if ( gb == END) {
i = 22 ;
}
return initialArray[ i] ;
}
private static int getCharValue ( char ch) {
String str = new String ( ) ;
str += ch;
try {
byte [ ] bytes = str. getBytes ( "GB2312" ) ;
if ( bytes. length < 2 ) {
return 0 ;
}
return ( bytes[ 0 ] << 8 & 0xff00 ) + ( bytes[ 1 ] & 0xff ) ;
} catch ( Exception e) {
return 0 ;
}
}
public static String getSentenceInitial ( String SourceStr ) {
String ret = "" ;
try {
for ( int i = 0 ; i < SourceStr . length ( ) ; i++ ) {
ret += char2Initial ( SourceStr . charAt ( i) ) ;
}
} catch ( Exception e) {
ret = "" ;
e. printStackTrace ( ) ;
}
return ret;
}
public static void main ( String [ ] args) throws Exception {
System . out. println ( getSentenceInitial ( "我爱你中国 I Love China" ) ) ;
}
}