今天在梳理銀行SQL業務的時候出現了一個全角的問題:兩個種代碼 都可以
使用了UDF函數解決
package 廣發; import org.apache.hadoop.hive.ql.exec.Description; import org.apache.hadoop.hive.ql.exec.UDF; @Description( name = "全角轉化半角", value = "this is a 全角轉化半角 util" ) public class Full2Half extends UDF { public String evaluate(String QJstr) throws Exception { StringBuilder outStrBuf = new StringBuilder(""); 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(); } }
我們來理解一下Java中全角字符和半角字符之間的關系
@Test public void test1() { for (int i = Character.MIN_VALUE; i <= Character.MAX_VALUE; ++i) { System.out.println(i + " " + (char)i); } }
從輸出可以看到
半角字符是從33開始到126結束
與半角字符對應的全角字符是從65281開始到65374結束
其中半角的空格是32.對應的全角空格是12288
半角和全角的關系很明顯,除空格外的字符偏移量是65248(65281-33 = 65248)
/** * 全角字符串轉換半角字符串 * * @param fullWidthStr * 非空的全角字符串 * @return 半角字符串 */ @Test private 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); }