`

Java转换全角半角

 
阅读更多

package com.breeze.util;

public class ChangeCode {

public static void main(String[] args) {

String QJstr = "abcdefghijklmnopqrstuvwxyz,.'?";
String QJstr2="abcdefghijklmnopqrstuvwxyz";

String result1 = Q2B(QJstr2);
String result2 = B2Q(QJstr);

System.out.println(result1);
System.out.println("/n"+result2);
}

private static String Q2B(String QJstr) {// 全角-->半角
String outStr = "";
String Tstr = "";
byte[] b = null;

for (int i = 0; i < QJstr.length(); i++) {
try {
Tstr = QJstr.substring(i, i + 1);
b = Tstr.getBytes("unicode");
} catch (java.io.UnsupportedEncodingException e) {
e.printStackTrace();
}

if (b[3] == -1) {
b[2] = (byte) (b[2] + 32);
b[3] = 0;

try {
outStr = outStr + new String(b, "unicode");
} catch (java.io.UnsupportedEncodingException e) {
e.printStackTrace();
}
} else
outStr = outStr + Tstr;
}

return outStr;
}

private static String B2Q(String QJstr){// 半角-->全角
String outStr = "";
String Tstr = "";
byte[] b = null;

for (int i = 0; i < QJstr.length(); i++) {
try {
Tstr = QJstr.substring(i, i + 1);
b = Tstr.getBytes("unicode");
} catch (java.io.UnsupportedEncodingException e) {
e.printStackTrace();
}

System.out.println(Tstr);
System.out.println("b[0]="+b[0]);
System.out.println("b[1]="+b[1]);
System.out.println("b[2]="+b[2]);
System.out.println("b[3]="+b[3]);
if (b[3] == 0) {
b[2] = (byte) (b[2] - 32);
b[3] = -1;

try {
outStr = outStr + new String(b, "unicode");
} catch (java.io.UnsupportedEncodingException e) {
e.printStackTrace();
}
} else
outStr = outStr + Tstr;
}

return outStr;
}
}

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics