java獲取中文拼音首字母工具類定義與用法例項
阿新 • • 發佈:2020-01-07
本文例項講述了java獲取中文拼音首字母工具類定義與用法。分享給大家供大家參考,具體如下:
package com.sw.documentary.common.utils; public class GB2Alpha { //字母Z使用了兩個標籤,這裡有27個值 //i,u,v都不做聲母,跟隨前面的字母 private char[] chartable = { '啊','芭','擦','搭','蛾','發','噶','哈','擊','喀','垃','媽','拿','哦','啪','期','然','撒','塌','挖','昔','壓','匝','座' }; private char[] alphatable = { 'A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z' }; private int[] table = new int[27]; //初始化 { for (int i = 0; i < 27; ++i) { table[i] = gbValue(chartable[i]); } } public GB2Alpha() { } //主函式,輸入字元,得到他的聲母,//英文字母返回對應的大寫字母 //其他非簡體漢字返回 '0' public char Char2Alpha(char ch) { if (ch >= 'a' && ch <= 'z') return (char) (ch - 'a' + 'A'); if (ch >= 'A' && ch <= 'Z') return ch; int gb = gbValue(ch); if (gb < table[0]) return '0'; int i; for (i = 0; i < 26; ++i) { if (match(i,gb)) break; } if (i >= 26) return '0'; else return alphatable[i]; } //根據一個包含漢字的字串返回一個漢字拼音首字母的字串 public String String2Alpha(String SourceStr){ String Result = ""; int StrLength = SourceStr.length(); int i; try { for (i = 0; i < StrLength; i++) { Result += Char2Alpha(SourceStr.charAt(i)); } } catch (Exception e) { Result = ""; } return Result; } private boolean match(int i,int gb) { if (gb < table[i]) return false; int j = i + 1; //字母Z使用了兩個標籤 while (j < 26 && (table[j] == table[i])) ++j; if (j == 26) return gb <= table[j]; else return gb < table[j]; } //取出漢字的編碼 private int gbValue(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 void main(String[] args) { GB2Alpha obj1 = new GB2Alpha(); System.out.println(obj1.String2Alpha("我們")); System.out.println(obj1.String2Alpha("歡迎你")); return; } }
執行結果:
JBZJ
HYN
PS:這裡再為大家提供幾款本站拼音與字母相關工具供大家參考:
線上中英文根據首字母排序工具:
http://tools.jb51.net/aideddesign/zh_paixu
線上漢字轉換成拼音工具:
http://tools.jb51.net/transcoding/pinyin
線上中文漢字轉拼音工具:
http://tools.jb51.net/transcoding/hanzi2pinyin
線上中文漢字拼音對照轉換工具:
http://tools.jb51.net/transcoding/zh_pinyin
線上字母大小寫轉換工具:
http://tools.jb51.net/transcoding/upper
更多關於java相關內容感興趣的讀者可檢視本站專題:《Java陣列操作技巧總結》、《Java字元與字串操作技巧總結》、《Java數學運算技巧總結》、《Java資料結構與演算法教程》及《Java操作DOM節點技巧總結》
希望本文所述對大家java程式設計有所幫助。