import java.io.UnsupportedEncodingException;
public class ChineseToEn {
private final static int[] secPosValue = {
1601,1637,1833,2078,2274,2302,2433,2594,
2787,3106,3212,3472,3635,3722,3730,3858,
4027,4086,4390,4558,4684,4925,5249,5590};
private final static String[] firstLetter = {
"a","b","c","d","e","f","g","h",
"j","k","l","m","n","o","p","q",
"r","s","t","w","x","y","z"
};
/**
* 获取所有汉字首字母
* @param str
* @return
*/
public String getAllFirstLetter(String str){
if (str == null || str.trim().length() == 0){
return "";
}
String _str = "";
for (int i = 0; i < str.length(); i++) {
_str = _str + this.getFirstLetter(str.substring(i,i+1));
}
return _str;
}
/**
* 获取第一个汉字首字母
* @param str
* @return
*/
private String getFirstLetter(String str) {
if (str == null || str.trim().length() == 0){
return "";
}
str = this.conversionStr(str,"GB2312","ISO8859-1");
if (str.length() > 1){
int sectorCode =(int)str.charAt(0);
int positionCode = (int)str.charAt(1);
sectorCode = sectorCode - 160;
positionCode = positionCode - 160;
int secPosCode = sectorCode * 100 + positionCode;
if(secPosCode > 1600 && secPosCode < 5590){
for (int i = 0; i < 23; i++) {
if (secPosCode >= secPosValue[i] && secPosCode < secPosValue[i+1]){
str = firstLetter[i];
break;
}
}
}else {
str =this.conversionStr(str, "ISO8859-1","GB2312");
str = str.substring(0,1);
}
}
return str;
}
/**
* 转换编码
* @param str
* @param oldchartset
* @param chartset
* @return
*/
private String conversionStr(String str, String oldchartset, String chartset) {
try {
str = new String(str.getBytes(oldchartset),chartset);
}catch (UnsupportedEncodingException e){
System.out.println("转换编码异常"+e.getMessage());
}
return str;
}
}
版权归属:
seems
许可协议:
本文使用《署名-非商业性使用-相同方式共享 4.0 国际 (CC BY-NC-SA 4.0)》协议授权
评论区