全角符跟半角符转换
一、在js中处理:
//转换为全角字符
function SBC(text) {
return text && text.replace(/[\x20-\x7e]/g, function($0) {
return $0 == " " ? "\u3000" : String.fromCharCode($0.charCodeAt(0) + 0xfee0);
});
}
//转换为半角字符
function CBS(text) {
return text && text.replace(/[\u3000\uff01-\uff5f]/g, function($0) {
return $0 == "\u3000" ? " " : String.fromCharCode($0.charCodeAt(0) - 0xfee0);
});
}
alert(SBC("zswang 2010"));
alert(CBS("zswang 2010"));
二、在java中处理
/**
* 半角转全角
* @param QJstr
* @return
*/
public static final String BQchange(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] = -1;
try {
outStr = outStr + new String(b, "unicode");
}catch (java.io.UnsupportedEncodingException e) {
e.printStackTrace();
}
}else{
outStr = outStr + tStr;
}
}
return outStr;
}
/**
* 全角转半角
* @param QJstr
* @return
*/
public static final String QBchange(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;
}
public static void main(String[] args){
System.out.println(QBchange("rewr()34#"));
}