/**
* @param args
*/
public static void main(String[] args) {
String str = "hello!! 全角转换,DAO 53232,、、 @#¥%……&*()。。。。。";
//String newstr = str.replaceAll("[\\pP‘’“”]", ""); //去掉标点(包括全半角)
//String newstr = str.replaceAll("\\pP", ""); //去掉标点(包括全半角)
String newstr = "";
try {
newstr = full2HalfChange(str);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
System.out.println("(全角转半角)转换前str1----------------------------"+str);
System.out.println("(全角转半角)转换后str1----------------------------"+newstr);
String _str = "java 汽车 召回 2345..!@#$%^&,,,,";
String _newstr = "";
try {
_newstr = half2Fullchange(_str);
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("(半角转全角)转换前str1----------------------------"+_str);
System.out.println("(半角转全角)转换后str1----------------------------"+_newstr);
}
/**
* 全角转半角
* @param QJstr
* @return
* @throws UnsupportedEncodingException
*/
public static final String full2HalfChange(String QJstr)
throws UnsupportedEncodingException {
StringBuffer outStrBuf = new StringBuffer("");
String Tstr = "";
byte[] b = null;
for (int i = 0; i < QJstr.length(); i++) {
Tstr = QJstr.substring(i, i + 1);
// 全角空格转换成半角空格
if (Tstr.equals(" ")) {
outStrBuf.append(" ");
continue;
}
b = Tstr.getBytes("unicode"); // 得到 unicode 字节数据
if (b[2] == -1) { // 表示全角?
b[3] = (byte) (b[3] + 32);
b[2] = 0;
outStrBuf.append(new String(b, "unicode"));
} else {
outStrBuf.append(Tstr);
}
}
return outStrBuf.toString();
}
/**
* 半角转全角
* @param QJstr
* @return
* @throws UnsupportedEncodingException
*/
public static final String half2Fullchange(String QJstr)
throws UnsupportedEncodingException {
StringBuffer outStrBuf = new StringBuffer("");
String Tstr = "";
byte[] b = null;
for (int i = 0; i < QJstr.length(); i++) {
Tstr = QJstr.substring(i, i + 1);
if (Tstr.equals(" ")) {
// 半角空格
outStrBuf.append(Tstr);
continue;
}
b = Tstr.getBytes("unicode");
if (b[2] == 0) {
// 半角?
b[3] = (byte) (b[3] - 32);
b[2] = -1;
outStrBuf.append(new String(b, "unicode"));
} else {
outStrBuf.append(Tstr);
}
}
return outStrBuf.toString();
}
}
经过我的严格测试,完全可以成功输出(但是"。"句号无论是全角转半角还是半角转全角都转换不过来)