如何检查字符串是否仅包含 ASCII? [英] How to check if a String contains only ASCII?

查看:42
本文介绍了如何检查字符串是否仅包含 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(空格)的不可打印字符,例如制表符、换行符/回车符以及BEL 带有代码 0x07DEL 带有代码 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.

对于没有 ascii() 方法的早期 Guava 版本,您可以编写:

For earlier Guava versions without the ascii() method you may write:

boolean isAscii = CharMatcher.ASCII.matchesAllOf(someString);

这篇关于如何检查字符串是否仅包含 ASCII?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆