java实现全角/半角的互相转换

阅读更多
重点:根据字母的偏移值重新计算其编码
// 把输入的字符串转换为半角
public String toDBCS(String str) {
        if (str == null) {
            return "";
        }
        StringBuffer sb = new StringBuffer();
        for (int i = 0, n = str.length(); i< n; i++) {
            int c = str.charAt(i);
            if ((c >= 'a') && (c<= 'z')) {
                c = (c + 'a') - 'a';
            } else if ((c >= 'A') &&(c <= 'Z')) {
                c = (c + 'A') - 'A';
            } else if ((c >= '0') &&(c <= '9')) {
                c = (c + '0') - '0';
            }
            sb.append((char) c);
        }
        return sb.toString();
    }

// 把输入的字符串转换为全角
   public String toSBCS(String str) {
        if (str == null) {
            return "";
        }
        StringBuffer sb = new StringBuffer();
        for (int i = 0, n = str.length(); i< n; i++) {
            int c = str.charAt(i);
            if ((c >= 'A') && (c <= 'Z')) {
                c = (c + 'A') - 'A';
            } else if ((c >= '0') && (c <= '9')) {
                c = (c + '0') - '0';
            } else if ((c >= 'a') && (c <= 'z')) {
                c = (c + 'a') - 'a';
            }
            sb.append((char) c);
        }
        return sb.toString();
    }


你可能感兴趣的:(Java,C,C++,C#)