本文主要是介绍获取中文汉字的首字母,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
package com.tbs.common.utils;import java.util.Random;public class ChinaInitialUtil {public static void main(String[] args) {String str = "河北省";System.out.println("中文首字母:" + getPYIndexStr(str, true));}/*** * 返回首字母* * @param strChinese* * @param bUpCase* * @return*/public static String getPYIndexStr(String strChinese, boolean bUpCase) {try {StringBuffer buffer = new StringBuffer();byte b[] = strChinese.getBytes("GBK");// 把中文转化成byte数组for (int i = 0; i < b.length; i++) {if ((b[i] & 255) > 128) {int char1 = b[i++] & 255;char1 <<= 8;// 左移运算符用“<<”表示,是将运算符左边的对象,向左移动运算符右边指定的位数,并且在低位补零。其实,向左移n位,就相当于乘上2的n次方int chart = char1 + (b[i] & 255);buffer.append(getPYIndexChar((char) chart, bUpCase));continue;}char c = (char) b[i];if (!Character.isJavaIdentifierPart(c))// 确定指定字符是否可以是 Java// 标识符中首字符以外的部分。c = 'A';buffer.append(c);}return buffer.toString();} catch (Exception e) {System.out.println((new StringBuilder()).append("\u53D6\u4E2D\u6587\u62FC\u97F3\u6709\u9519").append(e.getMessage()).toString());}return null;}/*** * 得到首字母* * @param strChinese* * @param bUpCase* * @return*/private static char getPYIndexChar(char strChinese, boolean bUpCase) {int charGBK = strChinese;char result;if (charGBK >= 45217 && charGBK <= 45252)result = 'A';elseif (charGBK >= 45253 && charGBK <= 45760)result = 'B';elseif (charGBK >= 45761 && charGBK <= 46317)result = 'C';elseif (charGBK >= 46318 && charGBK <= 46825)result = 'D';elseif (charGBK >= 46826 && charGBK <= 47009)result = 'E';elseif (charGBK >= 47010 && charGBK <= 47296)result = 'F';elseif (charGBK >= 47297 && charGBK <= 47613)result = 'G';elseif (charGBK >= 47614 && charGBK <= 48118)result = 'H';elseif (charGBK >= 48119 && charGBK <= 49061)result = 'J';elseif (charGBK >= 49062 && charGBK <= 49323)result = 'K';elseif (charGBK >= 49324 && charGBK <= 49895)result = 'L';elseif (charGBK >= 49896 && charGBK <= 50370)result = 'M';elseif (charGBK >= 50371 && charGBK <= 50613)result = 'N';elseif (charGBK >= 50614 && charGBK <= 50621)result = 'O';elseif (charGBK >= 50622 && charGBK <= 50905)result = 'P';elseif (charGBK >= 50906 && charGBK <= 51386)result = 'Q';elseif (charGBK >= 51387 && charGBK <= 51445)result = 'R';elseif (charGBK >= 51446 && charGBK <= 52217)result = 'S';elseif (charGBK >= 52218 && charGBK <= 52697)result = 'T';elseif (charGBK >= 52698 && charGBK <= 52979)result = 'W';elseif (charGBK >= 52980 && charGBK <= 53688)result = 'X';elseif (charGBK >= 53689 && charGBK <= 54480)result = 'Y';elseif (charGBK >= 54481 && charGBK <= 55289)result = 'Z';elseresult = (char) (65 + (new Random()).nextInt(25));if (!bUpCase)result = Character.toLowerCase(result);return result;}}
这篇关于获取中文汉字的首字母的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!