【问题标题】:Java Unicode replacement char with hex code用十六进制代码替换 Java Unicode 字符
【发布时间】:2014-12-31 03:10:51
【问题描述】:

我需要用转义字符“\”及其十六进制值替换字符串中的所有特殊 unicode 字符。 比如这个字符串:

String test="This is a string with the special è unicode char";

应替换为:

"This is a string with the special \E8 unicode char";

其中 E8 是 char "è" 的 unicode 值的十六进制值。

【问题讨论】:

  • 好的。你有没有尝试过?
  • 我有两个问题:如何找到“特殊字符”,如果每个字符值>127,我可以检查它吗?以及如何将十六进制值作为字符串。
  • 谷歌上的第一个结果"convert char to hex"
  • 要找到你的“特殊字符”,这取决于你认为什么特别。但是将其值与某个值进行比较是一个好的开始
  • 您当然知道,这不是您编写 Unicode 代码点的方式吗?那将是U+00E8。还有,你为什么要这样做?另一端应该如何解码?您将如何处理 BMP 之外的代码点?

标签: java string unicode


【解决方案1】:

如果您的 unicode 字符都在 \u0080 - \u00FF 范围内,您可以使用此解决方案。

public class Convert {

    public static void main(String[] args) {
        String in = "This is a string with the special è unicode char";
        StringBuilder out = new StringBuilder(in.length());

        for (int i = 0; i < in.length(); i++) {
            char charAt = in.charAt(i);
            if (charAt > 127) {
                // if there is a high number (several e.g. 100.000) of conversions
                // this lead in less objects to be garbadge collected
                out.append('\\').append(Integer.toHexString(charAt).toUpperCase());
                // out.append(String.format("\\%X", (int) charAt));
            } else {
                out.append(charAt);
            }
        }
        System.out.println(out);
    }
}

【讨论】:

    【解决方案2】:

    我正在尝试使用正则表达式替换此解决方案(我不知道是循环遍历字符串中的每个字符还是使用正则表达式...)

                    String test="This is a string with the special è unicode char";          
                    Pattern pat=Pattern.compile("([^\\x20-\\x7E])");            
                    int offset=0;           
                    Matcher m=pat.matcher(test);            
                    while(!m.hitEnd()) {
                        if (m.find(offset)) {
                            out.append(test.substring(offset,m.start()));               
                            for(int i=0;i<m.group(1).length();i++){
                              out.append(ESCAPE_CHAR);  
                              out.append(Integer.toHexString(m.group(1).charAt(i)).toUpperCase());
                            }                                           
                            offset=m.end();
                        }
    
                    }
                    return out.toString();
    

    【讨论】:

    • 我发布这个解决方案只是为了回答傲慢的评论“我们不会为你编码”。那不是我的要求,我只想知道是否有更聪明的方法来转义字符串,或者已经完成的操作,例如 StringUtils 中的方法
    【解决方案3】:

    我有两个问题:

    1)如何找到“特殊字符”,如果每个字符值>127,我可以检查它吗?

    这取决于您对“特殊”字符的定义。测试大于 127 的字符就是测试非 ASCII 字符。由您决定是否是您想要的。

    2) 以及如何将十六进制值作为字符串。

    Integer.toHexString 方法可以用于此。

    3) 我可以使用正则表达式来查找它还是为字符串的每个字符使用一个循环?

    循环更简单。

    【讨论】:

      猜你喜欢
      • 2022-11-19
      • 2017-06-28
      • 2016-02-13
      • 2012-02-21
      • 2014-12-28
      • 1970-01-01
      • 2014-03-10
      • 2018-11-12
      • 2017-11-17
      相关资源
      最近更新 更多