方法如下,是在论坛里看某位兄弟的方法,我在使用的时候发现转换某些中文的时候出现乱码,请各位大哥指点指点
例如: 0#a5465757oct342342042#13973119452#20051130201232#051212#保健一第一第一#省第一外科#主任#省第一1216#省第一上午
输出后变成:0#a5465757oct342342042#13973119452#20051130201232#051212#?∫坏谝坏谝?省第一外科#主任#省第一1216#省第一上午public static String getBjChnValue(String key) {
byte[] temp = key.getBytes();
int len = temp.length;
int qjlen = 0;
for (int m = 0; m < len; m++) { //计算全角字母的个数
if (temp[m] == -93) {
qjlen++;
m++;
}
}
byte[] ret = new byte[len - qjlen];
for (int i = 0, j = 0; j < len; i++, j++) {
if (temp[j] == -93) { //全角的
temp[j + 1] += 128;
ret[i] = temp[j + 1];
j++;
} else {
ret[i] = temp[j]; //普通的
}
}
String retString = new String(ret);
return retString;
}
例如: 0#a5465757oct342342042#13973119452#20051130201232#051212#保健一第一第一#省第一外科#主任#省第一1216#省第一上午
输出后变成:0#a5465757oct342342042#13973119452#20051130201232#051212#?∫坏谝坏谝?省第一外科#主任#省第一1216#省第一上午public static String getBjChnValue(String key) {
byte[] temp = key.getBytes();
int len = temp.length;
int qjlen = 0;
for (int m = 0; m < len; m++) { //计算全角字母的个数
if (temp[m] == -93) {
qjlen++;
m++;
}
}
byte[] ret = new byte[len - qjlen];
for (int i = 0, j = 0; j < len; i++, j++) {
if (temp[j] == -93) { //全角的
temp[j + 1] += 128;
ret[i] = temp[j + 1];
j++;
} else {
ret[i] = temp[j]; //普通的
}
}
String retString = new String(ret);
return retString;
}
{
// 半角转全角
public static String B2Q(String str)
{
StringBuffer sb = new StringBuffer();
for (int i = 0; i < str.length(); i ++)
{
sb.append((char)(str.charAt(i) + 65248));
}
return sb.toString();
}
// 全角转半角
public static String Q2B(String str)
{
StringBuffer sb = new StringBuffer();
for (int i = 0; i < str.length(); i ++)
{
char c = str.charAt(i);
if (c >=65281 && c < 65373)
sb.append((char)( c - 65248));
else
sb.append(str.charAt(i));
}
return sb.toString();
}
public static void main(String[] args)
{
// 测试工具类二
//String strQ = "123";
String strQ = "0#a5465757oct342342042#13973119452#20051130201232#051212#保健一第一第一#省第一外科#主任#省第一1216#省第一上午";
String strB = ",dfa@";
System.out.println("strQ="+strQ+" strB="+strB);
System.out.println("B2Q(strB)="+B2Q(strB));
System.out.println("Q2B(strQ)="+Q2B(strQ));
}
}
strQ=0#a5465757oct342342042#13973119452#20051130201232#051212#保健一第一第一#
省第一外科#主任#省第一1216#省第一上午 strB=,dfa@
B2Q(strB)=,dfa@
Q2B(strQ)=0#a5465757oct342342042#13973119452#20051130201232#051212#保健一第一第
一#省第一外科#主任#省第一1216#省第一上午
不过有个 小小的地方
如果 String strB = ",dfaf@a@";即其中既有 全角也有半角则 B2Q()方法有bug
// 半角转全角
public static String B2Q(String str)
{
StringBuffer sb = new StringBuffer();
for (int i = 0; i < str.length(); i ++)
{
char c = str.charAt(i);
if(c >=65281 && c < 65373)
sb.append((char)c);
else
sb.append((char)(c + 65248));
}
return sb.toString();
}
}