Determine if characters in a string are all of a specific character set(确定字符串中的字符是否都属于特定字符集)
问题描述
我需要能够在 Java 中获取一个字符串并确定其中包含的所有字符是否都在指定的字符集(例如 ISO-8859-1)中.我已经四处寻找一种简单的方法来做到这一点(包括使用 CharsetDecoder
),但还没有找到一些东西.
I need to be able to take a string in Java and determine whether or not all of the characters contained within it are in a specified character set (e.g. ISO-8859-1). I've looked around quite a bit for a simple way to do this (including playing around with a CharsetDecoder
), but have yet to be able to find something.
获取字符串并确定所有字符是否在给定字符集中的最佳方法是什么?
What is the best way to take a string and determine if all the characters are within a given character set?
推荐答案
Class CharsetEncoder 包 java.nio.charset 提供了一种方法 canEncode 测试是否支持特定字符.
Class CharsetEncoder in package java.nio.charset offer a method canEncode to test if a specific character is supported.
Michael 基本上是这样做的:
字符集
.forName
( CharEncoding.ISO_8859_1
).newEncoder
().canEncode
("字符串")
Charset
.forName
( CharEncoding.ISO_8859_1
).newEncoder
().canEncode
("string")
请注意,CharEncoding.ISO_8859_1
依赖于 Apache commons 并且可能被替换为ISO_8859_1".
Note that CharEncoding.ISO_8859_1
rely on Apache commons and may be replaced by "ISO_8859_1".
这篇关于确定字符串中的字符是否都属于特定字符集的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!