Hive中遇到全角

今天在梳理银行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);
}
原文地址:https://www.cnblogs.com/wqbin/p/10234702.html