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?
str , bytes , and bytearray gained support for the new isascii() method, which can be used to test if a string or bytes contain only the ASCII characters.
isascii() will check if the strings is ascii. "\x03". isascii() is also True.
Just paste your ASCII text in the input area and you will instantly get the ASCII status in the output area. If the input contains only ASCII characters, you'll get a green badge, otherwise a red badge. Fast, free, and without ads. Import ASCII – get ASCII status.
From Guava 19.0 onward, you may use:
boolean isAscii = CharMatcher.ascii().matchesAllOf(someString);
This uses the matchesAllOf(someString)
method which relies on the factory method ascii()
rather than the now deprecated ASCII
singleton.
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
.
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.
For earlier Guava versions without the ascii()
method you may write:
boolean isAscii = CharMatcher.ASCII.matchesAllOf(someString);
You can do it with java.nio.charset.Charset.
import java.nio.charset.Charset; public class StringUtils { public static boolean isPureAscii(String v) { return Charset.forName("US-ASCII").newEncoder().canEncode(v); // or "ISO-8859-1" for ISO Latin 1 // or StandardCharsets.US_ASCII with JDK1.7+ } public static void main (String args[]) throws Exception { String test = "Réal"; System.out.println(test + " isPureAscii() : " + StringUtils.isPureAscii(test)); test = "Real"; System.out.println(test + " isPureAscii() : " + StringUtils.isPureAscii(test)); /* * output : * Réal isPureAscii() : false * Real isPureAscii() : true */ } }
Detect non-ASCII character in a String
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With