Java全角半角字符转换
程序员文章站
2022-05-26 17:55:51
...
ASCII 编码表:ASCII 编码表
Unicode 编码表:Unicode 编码表
参考博客:https://blog.csdn.net/xyw591238/article/details/51719747
/**
* 全角、半角转换工具
*/
public class DBCSBCUtil {
public static final char SBC_SPACE = 12288; // 全角空格 12288
public static final char DBC_SPACE = 32; // 半角空格 32
// ASCII character 33-126 <-> unicode 65281-65374
public static final char ASCII_START = 33; // 可见字符“!”索引
public static final char ASCII_END = 126; // 可见字符“~”索引
public static final char UNICODE_START = 65281; // “!”的全角 Unicode 编码表索引
public static final char UNICODE_END = 65374; // “~”的全角 Unicode 编码表索引
public static final char DBC_SBC_STEP = 65248; // 全角半角转换间隔
public static char sbc2dbc(char src){
if (src == SBC_SPACE) {
return DBC_SPACE;
}
if (src >= UNICODE_START && src <= UNICODE_END) {
return (char) (src - DBC_SBC_STEP);
}
return src;
}
/**
* Convert from SBC case to DBC case
* 全角转半角
*/
public static String sbc2dbcCase(String src) {
if (src == null) {
return null;
}
char[] c = src.toCharArray();
for (int i = 0; i < c.length; i++) {
c[i] = sbc2dbc(c[i]);
}
return new String(c);
}
public static char dbc2sbc(char src){
if (src == DBC_SPACE) {
return SBC_SPACE;
}
if (src <= ASCII_END) {
return (char) (src + DBC_SBC_STEP);
}
return src;
}
/**
* Convert from DBC case to SBC case.
* 半角转全角
*/
public static String dbc2sbcCase(String src) {
if (src == null) {
return null;
}
char[] c = src.toCharArray();
for (int i = 0; i < c.length; i++) {
c[i] = dbc2sbc(c[i]);
}
return new String(c);
}
}