How to Check if a String contains only ASCII in Java?
Last Updated :
12 Feb, 2024
The full form of ASCII is the American Standard Code for Information Interchange. It is the numeric representation of Character. As Java supports multiple languages, and it follows the Unicode system. In simple terms for better understanding, it converts the Character to a specific unique number, and then the number converts to the machine-level code, and the range of ASCII value is 0 to 127, and now we want to check whether a string only contains ASCII characters. We can use String.matches() method and passes a Regex (regular expressions) in it, and it returns a boolean value.
Checking If String Contains Only ASCII Characters
So, we have two strings s1 and s2, s1 contains only ASCII characters and the second string s2 contains some special or non-ASCII characters.
Input:
// contains ASCII characters
s1 = "GeeksforGeeks"
// contains non-ASCII character
s2 = "€_is_a_Symbol_of_euro"
Below is the program for Checking If the String Contains Only ASCII Characters:
Java
import java.io.*;
class GFG {
public static void main(String[] args)
{
String s1 = "GeeksforGeeks" ;
String s2 = "€_is_a_Symbol_of_euro" ;
System.out.println(
"is s1 contains only ASCII characters :"
+ s1.matches( "\\A\\p{ASCII}*\\z" ));
System.out.println(
"is s2 contains only ASCII characters :"
+ s2.matches( "\\A\\p{ASCII}*\\z" ));
}
}
|
Output
is s1 contains only ASCII characters :true
is s2 contains only ASCII characters :false
Another Approach
We know that the range of ASCII value is between 0 to 127 so if the characters Unicode is not lies in this range so the string contains non-ASCII character.
Approach:
- So first we create a boolean variable and set it’s default value true.
- Because we initially assumes that the string only contains the ASCII character
- Then we iterate through each characters and checks it’s range. if it not lie in the range 0 to 127 so we set boolean variable’s value as false.
- And print the output on console.
Java
import java.io.*;
class GFG {
public static void main(String[] args)
{
String s1 = "GeeksforGeeks" ;
String s2 = "€_is_a_Symbol_of_euro" ;
boolean checkASCII_for_s1 = true ;
boolean checkASCII_for_s2 = true ;
for ( int i = 0 ; i < s1.length(); i++) {
int Char = s1.charAt(i);
if (Char > 127 ) {
checkASCII_for_s1 = false ;
break ;
}
}
for ( int i = 0 ; i < s2.length(); i++) {
int Char = s2.charAt(i);
if (Char > 127 ) {
checkASCII_for_s2 = false ;
break ;
}
}
System.out.println(
"is s1 contains only ASCII characters :"
+ checkASCII_for_s1);
System.out.println(
"is s2 contains only ASCII characters :"
+ checkASCII_for_s2);
}
}
|
Output
is s1 contains only ASCII characters :true
is s2 contains only ASCII characters :false
Share your thoughts in the comments
Please Login to comment...