为了保持简单和健壮,请利用CharsetEncoder:
/** replaces any invalid character in Latin1 by the character rep */
public static String latin1(String str, char rep) {
CharsetEncoder cs = StandardCharsets.ISO_8859_1.newEncoder()
.onMalformedInput(CodingErrorAction.REPLACE)
.onUnmappableCharacter(CodingErrorAction.REPLACE)
.replaceWith(new byte[] { (byte) rep });
try {
ByteBuffer b = cs.encode(CharBuffer.wrap(str));
return new String(b.array(), StandardCharsets.ISO_8859_1);
} catch (CharacterCodingException e) {
throw new RuntimeException(e); // should not happen
}
}
这会将 ISO_8859_1 (= Latin1) 中的每个无效字符集替换为替换字符 rep(当然,它应该是一个有效的 Latin1 字符)。
如果你对默认替换('?')没问题,你可以让它更简单:
public static String latin1(String str) {
return new String(str.getBytes(StandardCharsets.ISO_8859_1),
StandardCharsets.ISO_8859_1);
}
例如:
public static void main(String[] args) {
String x = "hi Œmar!";
System.out.println("'" + x + "' -> '" + latin1(x,'?') + "'");
}
输出'hi Œmar!' -> 'hi ?mar!'
这种方法的一个可能缺点是只允许您用单个替换字符替换每个无效字符 - 您不能删除它或使用多字符序列。
如果你想要这个,并且如果你有理由确定某些字符永远不会出现在你的字符串中,你可以采用通常的肮脏技巧 - 例如,假设 \u0000 永远不会出现:
/* removes invalid Latin1 charaters - assumes the zero character never appears */
public static String latin1removeinvalid(String str) {
return latin1(str,(char)0).replace("\u0000", "");
}
补充:如果你只想检查有效性,那就更简单了:
public static boolean isValidLatin1(String str) {
return StandardCharsets.ISO_8859_1.newEncoder().canEncode(str);
}