首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >如何验证UTF-8字符串是否包含错误编码的字符

如何验证UTF-8字符串是否包含错误编码的字符
EN

Stack Overflow用户
提问于 2013-01-09 22:00:25
回答 2查看 33.2K关注 0票数 18

在一个大型数据集中,我有一些看起来像这样的数据:

代码语言:javascript
复制
"guide (but, yeah, it’s okay to share it with ‘em)."

我已经在十六进制编辑器中打开了该文件,并通过字符编码检测算法(http://code.google.com/p/juniversalchardet/)运行原始字节数据,它被确定为UTF8。

在我看来,数据的来源错误地解释了原始字符集,并将有效的UTF-8作为我收到的输出。

我想尽我所能验证数据。是否有任何启发式/算法可以帮助我尝试验证?

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2013-01-09 22:04:05

一旦你有了字符串,你就不能这样做,你必须在你仍然有原始输入的时候这样做。一旦有了字符串,就没有办法在没有一些非常脆弱的测试的情况下自动判断’是否是预期的输入。例如:

代码语言:javascript
复制
public static boolean isUTF8MisInterpreted( String input ) {
          //convenience overload for the most common UTF-8 misinterpretation
          //which is also the case in your question
      return isUTF8MisInterpreted( input, "Windows-1252");  
}

public static boolean isUTF8MisInterpreted( String input, String encoding) {

    CharsetDecoder decoder = Charset.forName("UTF-8").newDecoder();
    CharsetEncoder encoder = Charset.forName(encoding).newEncoder();
    ByteBuffer tmp;
    try {
        tmp = encoder.encode(CharBuffer.wrap(input));
    }

    catch(CharacterCodingException e) {
        return false;
    }

    try {
        decoder.decode(tmp);
        return true;
    }
    catch(CharacterCodingException e){
        return false;
    }       
}

public static void main(String args[]) {
    String test = "guide (but, yeah, it’s okay to share it with ‘em).";
    String test2 = "guide (but, yeah, it’s okay to share it with ‘em).";
    System.out.println( isUTF8MisInterpreted(test)); //true
    System.out.println( isUTF8MisInterpreted(test2)); //false

}

如果您仍然可以访问原始输入,则可以使用以下命令查看字节数组是否等于完全有效的utf-8字节序列:

代码语言:javascript
复制
public static boolean isValidUTF8( byte[] input ) {

    CharsetDecoder cs = Charset.forName("UTF-8").newDecoder();

    try {
        cs.decode(ByteBuffer.wrap(input));
        return true;
    }
    catch(CharacterCodingException e){
        return false;
    }       
}

也可以对流使用CharsetDecoder,默认情况下,一旦发现给定编码中的无效字节,它就会抛出异常。

票数 38
EN

Stack Overflow用户

发布于 2015-12-15 13:58:10

如果您使用的是HTML5,那么只需在<head>中添加<meta charset="UTF-8">

对于HTML4 <meta http-equiv="Content-type" content="text/html;charset=UTF-8">

票数 -4
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/14236923

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档