2

In order to check whether the string of characters are ASCII or not. 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
  2. Convert the String to character array and use : org.apache.commons.lang.CharUtils.isAscii() method to check whether 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.

NEO
  • 161
  • 1
  • 3
  • 10
  • some more choices to do [here](http://stackoverflow.com/questions/3585053/in-java-is-it-possible-to-check-if-a-string-is-only-ascii) – Ankur Singhal Nov 05 '15 at 04:41

1 Answers1

1

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.

Regards.

Doc
  • 10,831
  • 3
  • 39
  • 63
  • `asciiText.matches("\\p{ASCII}*");` Can be used to check ASCII, why have you used `asciiText.matches("\\A\\p{ASCII}*\\z")` ? – NEO Nov 06 '15 at 08:34
  • @NEO oops I thought you needed alphabets. yes, asciiText.matches("\\p{ASCII}*"); would be fine – Doc Nov 06 '15 at 09:07