是否可以检查String是否只包含ASCII? [英] Is it possible to check if a String only contains ASCII?
问题描述
如果字符是字母,则调用 Character.isLetter(c)
返回 true
。但有没有办法快速查找 String
是否只包含ASCII的基本字符?
The call Character.isLetter(c)
returns true
if the character is a letter. But is there a way to quickly find if a String
only contains the base characters of ASCII?
推荐答案
从 Guava 19.0开始,您可以使用:
From Guava 19.0 onward, you may use:
boolean isAscii = CharMatcher.ascii().matchesAllOf(someString);
这使用 matchesAllOf(someString)
依赖于工厂方法的方法 ascii()
而不是现在弃用的 ASCII
单身。
此处ASCII包括所有ASCII字符,包括低于 0x20 $ c $的不可打印字符c>(空格),例如标签,换行/返回,还有
BEL
,代码 0x07
和 DEL
代码 0x7F
。
Here ASCII includes all ASCII characters including the non-printable characters lower than 0x20
(space) such as tabs, line-feed / return but also BEL
with code 0x07
and DEL
with code 0x7F
.
此代码错误地使用字符而非代码点,即使代码点在早期版本的注释中指出。幸运的是,创建值为 U + 010000
或更高的代码点所需的字符使用两个代理字符,其值超出ASCII范围。所以该方法仍然成功地测试了ASCII,即使对于包含表情符号的字符串也是如此。
This code incorrectly uses characters rather than code points, even if code points are indicated in the comments of earlier versions. Fortunately, the characters required to create code point with a value of U+010000
or over uses two surrogate characters with a value outside of the ASCII range. So the method still succeeds in testing for ASCII, even for strings containing emoji's.
对于没有的早期Guava版本ascii()
你可以编写的方法:
For earlier Guava versions without the ascii()
method you may write:
boolean isAscii = CharMatcher.ASCII.matchesAllOf(someString);
这篇关于是否可以检查String是否只包含ASCII?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!