1. public class GetFirstLetter {标签:Java,String,int,bytes,汉语拼音,private,char,首字母,static From: https://blog.51cto.com/u_15070324/6088369
2.
3. private static final int GB_SP_DIFF = 160;
4. private static final int[] secPosvalueList = {
5. 1601, 1637, 1833, 2078, 2274, 2302, 2433, 2594, 2787,
6. 3106, 3212, 3472, 3635, 3722, 3730, 3858, 4027, 4086,
7. 4390, 4558, 4684, 4925, 5249, 5600};
8. private static final char[] firstLetter = {
9. 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'j',
10. 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's',
11. 't', 'w', 'x', 'y', 'z'};
12.
13. public static String getFirstLetter(String oriStr) {
14. String str = oriStr.toLowerCase();
15. StringBuffer buffer = new StringBuffer();
16. char ch;
17. char[] temp;
18. for (int i = 0; i < str.length(); i++) {
19. ch = str.charAt(i);
20. temp = new char[] {
21. ch};
22. byte[] uniCode = new String(temp).getBytes();
23. if (uniCode[0] < 128 && uniCode[0] > 0) {
24. buffer.append(temp);
25. }
26. else {
27. buffer.append(convert(uniCode));
28. }
29. }
30. return buffer.toString().substring(0,1);
31. }
32.
33. private static char convert(byte[] bytes) {
34.
35. char result = '-';
36. int secPosvalue = 0;
37. int i;
38. for (i = 0; i < bytes.length; i++) {
39. bytes[i] -= GB_SP_DIFF;
40. }
41. secPosvalue = bytes[0] * 100 + bytes[1];
42. for (i = 0; i < 23; i++) {
43. if (secPosvalue >= secPosvalueList[i] &&
44. secPosvalue < secPosvalueList[i + 1]) {
45. result = firstLetter[i];
46. break;
47. }
48. }
49. return result;
50. }
51.
52. public static void main(String s[]){
53.
54. System.out.print(getFirstLetter("好"));
55. }