Contents

程式半型轉全型方法

Contents

Keep Learning…

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
public class HelloWorld{

     public static void main(String []args){
        System.out.println(halfWidth2FullWidth("Hello World!!!@"));
        System.out.println(fullWidth2halfWidth("Hello World!!!@"));
        System.out.println(halfWidth2FullWidth("Hello World!!!@中文測試"));
        System.out.println(fullWidth2halfWidth("中文測試Hello World!!!@"));
     }
     
    /**
 * Full-angle string conversion half-corner string
 * 1, half-width characters are starting from 33 to 126 end
 * 2, the full-width character corresponding to the half-width character is from 65281 start to 65374 end
 * 3, the half corner of the space is 32. The corresponding Full-width space is 12288
 * The relationship between Half-width and Full-width is obvious, except that the character offset is 65248 (65281-33 = 65248).
 *
 * @param fullWidthStr Non-empty full-width string
 * @return Half-angle string
 */
public static  String halfWidth2FullWidth(String fullWidthStr) {
    if (null == fullWidthStr || fullWidthStr.length() <= 0) {
        return "";
    }
    char[] arr = fullWidthStr.toCharArray();
    for (int i = 0; i < arr.length; ++i) {
        int charValue = (int) arr[i];
        if (charValue >= 33 && charValue <= 126) {
            arr[i] = (char) (charValue + 65248);
        } else if (charValue == 32) {
            arr[i] = (char) 12288;
        }
    }
    return new String(arr);
}

   private static String fullWidth2halfWidth(String fullWidthStr) {
        if (null == fullWidthStr || fullWidthStr.length() <= 0) {
            return "";
        }
        char[] charArray = fullWidthStr.toCharArray();
        //對全形字元轉換的char陣列遍歷
        for (int i = 0; i < charArray.length; i++) {
            int charIntValue = (int) charArray[i];
            //如果符合轉換關係,將對應下標之間減掉偏移量65248;如果是空格的話,直接做轉換
            if (charIntValue >= 65281 && charIntValue <= 65374) {
                charArray[i] = (char) (charIntValue - 65248);
            } else if (charIntValue == 12288) {
                charArray[i] = (char) 32;
            }
        }
        return new String(charArray);
    }
}