转自:http://blog.youkuaiyun.com/wanghangzhou1984/article/details/5950440
import java.io.UnsupportedEncodingException;
public class FullCharConverter {
public static void main(String[] args) throws UnsupportedEncodingException {
// 全角转半角
String QJstr = "hello!! 全角转换,DAO 53232 ";
String result = full2HalfChange(QJstr);
System.out.println(QJstr);
System.out.println(result);
System.out.println("------------------------------------");
// 半角转全角
String str = "java 汽车 召回 2345";
System.out.println(str);
System.out.println(half2Fullchange(str));
}
// 全角转半角的 转换函数
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);
}
} // end for.
return outStrBuf.toString();
}
// 半角转全角
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();
}
}
本文介绍了一种使用Java实现的全角字符与半角字符之间的相互转换方法。通过两个核心函数,可以将字符串中的全角字符转换为对应的半角字符,反之亦然。这些函数适用于处理包含混合全角和半角字符的文本数据。
7398

被折叠的 条评论
为什么被折叠?



