How to Check if a String contains only ASCII in Java ?

The American Standard Code for Information Interchange is ASCII in its whole form. It is a Character represented numerically. Java uses the Unicode system and supports a number of languages. For the benefit of conciseness, let us understand that it first converts the character to a unique number, which is then converted to machine-level code. The range of ASCII values is 0 to 127. At this point, we want to determine if a string exclusively contains ASCII characters. The String.matches() method can be used, and it returns a boolean value when a Regex (regular expression) has been passed in.

Approach: Using String.matches()

Checking whether two strings contain just ASCII characters is the method used by the Java program provided. To do this check, it uses the String.matches() method and the regular expression \\A\\p{ASCII}*\\z. \\A\\p{ASCII}*\\z is a regular expression that guarantees that only ASCII characters (\\p{ASCII}) are used throughout the string, from start (\\A) to finish (\\z). The two strings that the software specifies are called s1 and s2, where s1 only has ASCII characters and s2 has both ASCII and non-ASCII characters. Next, for every string, it prints the outcome of the ASCII check.

Implementation:

FileName: AsciiChecking.java

Output:

Is the String s1 contains only ASCII characters :true
Is the String s2 contains only ASCII characters :true

Approach: Using for Loop

Considering the ASCII value range is known to be between 0 and 127, a string containing non-ASCII characters is present if any Unicode characters fall outside of this range.

Algorithm:

Step 1: We first define a boolean variable and set true to be its default value.

Step 2: Since we first considered the string to contain solely ASCII characters

Step 3: Next, we go over each character one by one and determine its range. If it does not fall between 0 and 127, we set the value of the boolean variable to false.

Step 4: In a console window, print the result.

Implementation:

FileName: AsciiValuePrediction.java

Output:

Is the String str1 contains only ASCII characters :true
Is the String str2 contains only ASCII characters :true

Complexity Analysis:

The above program's time complexity is O(N1 + N2), where N1 and N2 are the lengths of str1 and str2, respectively, and the Space Complexity is O(1).