JAVA实现全角半角相互转化 (full2Half & half2Full)

说明:

1.全角:指一个字符占用两个标准字符位置。汉字字符和规定了全角的英文字符及国标GB2312-80中的图形符号和特殊字符都是全角字符。一般的系统命令是不用全角字符的,只是在作文字处理时才会使用全角字符。

2.半角:指一字符占用一个标准的字符位置。通常的英文字母、数字键、符号键都是半角的,半角的显示内码都是一个字节。在系统内部,以上三种字符是作为基本代码处理的,所以用户输入命令和参数时一般都使用半角。

 
范围(无空格):

全角字符unicode编码从65281~65374(十六进制0xFF01 ~ 0xFF5E)
半角字符unicode编码从33~126(十六进制0x21~ 0x7E)

特例:
空格比较特殊,全角为12288(0x3000),半角为 32(0x20)

注:

1. 中文文字永远是全角,只有英文字母、数字键、符号键才有全角半角的概念,一个字母或数字占一个汉字的位置叫全角,占半个汉字的位置叫半角。

2. 引号在中英文、全半角情况下是不同的。


JAVA代码参考
全角转半角

         /**
         *
         * @Title: convertStringFromFullWidthToHalfWidth.
         * @Description: Convert a String from half width to full width.
         *
         * @param string input string
         * @return the converted String
         */
        public static String full2Half(String string) {
            if (isEmpty(string)) {
                return string;
            }
            
            char[] charArray = string.toCharArray();
            for (int i = 0; i < charArray.length; i++) {
                if (charArray[i] == 12288) {
                    charArray[i] =' ';
                } else if (charArray[i] >= ' ' &&
                        charArray[i]  <= 65374) {
                    charArray[i] = (char) (charArray[i] - 65248);
                } else {
                    
                }
            }
     
     
            return new String(charArray);
        }


半角转全角:

    /**
         * this is used to convert half to full-widths charaters.
        * @Title: half2Full
        * @param value input value
        * @return converted value
         */
        public static String half2Full(String value) {
            if (isEmpty(value)) {
                return "";
            }
            char[] cha = value.toCharArray();
     
            /**
             * full blank space is 12288, half blank space is 32
             * others :full is 65281-65374,and half is 33-126.
             */
            for (int i = 0; i < cha.length; i++) {
                if (cha[i] == 32) {
                    cha[i] = (char) 12288;
                } else if (cha[i] < 127) {
                    cha[i] = (char) (cha[i] + 65248);
                }
            }
            return new String(cha);
        }
     
        /**
         * @Description: check whether is empty.
         * @Title: isEmpty
         * @param str input string
         * @return whether the input is empty
         */
        public static boolean isEmpty(String str) {
            return str == null || str.length() == 0;
        }
---------------------  
作者:数据中国  
来源:CSDN  
原文:https://blog.csdn.net/chndata/article/details/47334253  
版权声明:本文为博主原创文章,转载请附上博文链接!

猜你喜欢

转载自blog.csdn.net/SeaSky_Steven/article/details/87453889