简体   繁体   English

如何在Java中检查字符串是否为ASCII

[英]How To check whether the string of characters are ASCII in Java

In order to check whether the string of characters are ASCII or not.为了检查字符串是否为ASCII。 Which one of the below is better choice ?以下哪一项是更好的选择?

  1. java.nio.charset.Charset.forName("US-ASCII").newEncoder().canEncode("Desire character string to be checked") or java.nio.charset.Charset.forName("US-ASCII").newEncoder().canEncode("Desire character string to be checked")
  2. Convert the String to character array and use : org.apache.commons.lang.CharUtils.isAscii() method to check whether ASCII.将 String 转换为字符数组并使用 : org.apache.commons.lang.CharUtils.isAscii()方法检查是否为 ASCII。

What are their differences, and which one is good performance wise.他们有什么区别,哪一个是好的性能明智的。 I know for the second option there is additional step of converting string to the character array first and then, need to check each character.我知道对于第二个选项,首先需要将字符串转换为字符数组,然后需要检查每个字符。

You can use regex as a quick shortcut.您可以使用正则表达式作为快捷方式。

String asciiText = "Hello";
System.out.println(asciiText.matches("\\A\\p{ASCII}*\\z"));

this will check only ASCII characters.这将只检查 ASCII 字符。

Regards.问候。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM