【问题标题】:Remove Non-Ansi Chars from a UTF String and Keep Others从 UTF 字符串中删除非 Ansi 字符并保留其他字符
【发布时间】:2013-06-24 12:23:09
【问题描述】:

我们有一个接受 UTF8 字符串作为输入的 java 库。但是,如果输入中有任何非 ansi 字符的字符,则库可能会崩溃。因此,我们要从字符串中删除所有非 ansi 字符。但是如何在 java 中做到这一点呢?

谢谢,

【问题讨论】:

  • 到目前为止你尝试过什么?
  • 修复你的图书馆。这将有很大帮助

标签: java utf-8 encode ansi


【解决方案1】:

试试这个,我是从here 提取的,所以没有测试过

// Create a encoder and decoder for the character encoding
Charset charset = Charset.forName("US-ASCII");
CharsetDecoder decoder = charset.newDecoder();
CharsetEncoder encoder = charset.newEncoder();

// This line is the key to removing "unmappable" characters.
encoder.onUnmappableCharacter(CodingErrorAction.IGNORE);
String result = inString;

try {
    // Convert a string to bytes in a ByteBuffer
    ByteBuffer bbuf = encoder.encode(CharBuffer.wrap(inString));

    // Convert bytes in a ByteBuffer to a character ByteBuffer and then to a string.
    CharBuffer cbuf = decoder.decode(bbuf);
    result = cbuf.toString();
} catch (CharacterCodingException cce) {
    String errorMessage = "Exception during character encoding/decoding: " + cce.getMessage();
    cce.printStackTrace()
}

【讨论】:

    【解决方案2】:

    看看 String.codePointAt(index)。这可以为您提供给定字符的 Unicode 代码点,然后您可以从那里删除范围之外的那些。

    如何处理字符已被删除的事实取决于您自己,但请记住,您将发送到库的字符串不一定与客户端提供的字符串相同。这可能会也可能不会导致问题。

    我不确定您在这里所说的 ANSI 是什么意思。您是指人们通常称为 ANSI 的 Windows 1252 字符编码吗?这不是 ASCII,也不是 IS0-8859-1,因此请确保您的代码页正确无误。

    【讨论】:

      猜你喜欢
      • 2012-08-22
      • 2010-12-31
      • 2018-01-23
      • 1970-01-01
      • 2022-11-22
      • 2018-01-05
      • 2021-03-26
      • 1970-01-01
      • 2014-01-07
      相关资源
      最近更新 更多