引用 使用Java得到汉字的拼音首字母

 

引用java

恐龙007使用Java得到汉字的拼音首字母

因为工做中须要从汉字中提取其拼音首字母,为了偷懒^_^....本人写了如下类实现了自动将汉字转化为其拼音首字母.c++

能够直接提取如下类中的方法,并应用到其余场合下.测试

因为写的比较仓促,对该类只进行了大概的测试,所以本人并不保证代码百分之百的正确,请谅解...编码

package com.test;code

import java.io.UnsupportedEncodingException;blog

public class PinYin {字符串

 /**
  *汉字拼音的首字母,不存在i,u,v
  */
 private final static int[] HanZiCode = { 0xB0A1, 0xB0C5, 0xB2C1, 0xB4EE,
   0xB6EA, 0xB7A2, 0xB8C1, 0xB9FE, 0xBBF7, 0xBFA6, 0xC0AC, 0xC2E8,
   0xC4C3, 0xC5B6, 0xC5BE, 0xC6DA, 0xC8BB, 0xC8F6, 0xCBFA, 0xCDDA,
   0xCEF4, 0xD1B9, 0xD4D1, 0xD8A0 };
 private final static int LENGTH = HanZiCode.length;get

 /**
  * string


  * 该方法用于得到传入的汉字的首字母
  * io


  *


  * 若是传入的word不属于GB2312所包含的汉字,则原样返回
  *


  *

若是传入多个汉字,则原样返回


  * @param word
  *            String型值
  */
 public String getPinYin(String word) {
  byte[] byte1;
  char c = 'a' - 1;
  try {
   byte1 = word.getBytes("gb2312");
   if (byte1.length == 2) {
    int codeValue = ((byte1[0] + 256) * 256 + byte1[1] + 256);
    if (codeValue >= HanZiCode[0]
      && codeValue <= HanZiCode[LENGTH - 1]) {
     for (int i = 0; i < LENGTH; i++) {
      if (codeValue >= HanZiCode[i]) {
       if ((c + 1 == 'i')) {
        c += 2;
       }else if(c+1=='u'){
        c+=3;
       } else {
        c++;
       }
      }
     }
     return c + "";
    }
   }
  } catch (UnsupportedEncodingException e1) {
   e1.printStackTrace();
  }
  return word;
 }

 /**
  *得到传入字符串中每一个汉字拼音的首字母
  */
 public String chinese2PinYin(String str){
  int length=str.length();
  String result="";
  for(int i=0;i
   result+=getPinYin(str.substring(i, i+1));
  }
  return result;
 }
 /**
  * @param args
  * @throws UnsupportedEncodingException
  */
 public static void main(String[] args) throws UnsupportedEncodingException {
  // TODO Auto-generated method stub
  PinYin py = new PinYin();
  System.out.println(py.chinese2PinYin("汉字转拼音"));
 }

}

 

对该类若有疑问请留言,本人将及时予以答复..

对于其原理感兴趣的朋友能够参考GB2312的编码表

相关文章
相关标签/搜索