Is it possible to check if a String only contains ASCII in java?


Using regular expression

You can find whether a particular String value contains ASCII characters using the following regular expression −

\A\p{ASCII}*\z

The matches() method of the String class accepts a regular expression and verifies whether the current string matches the given expression if so, it returns true, else it returns false.

Therefore, Invoke the matches() method on the input/required string by passing the above specified regular expression as a parameter.

Example

 Live Demo

import java.util.Scanner;
public class OnlyASCII {
   public static void main(String[] args) {
      Scanner sc = new Scanner(System.in);
      System.out.println("Enter a string value: ");
      String input = sc.nextLine();
      //Verifying for ACCII
      boolean result = input.matches("\A\p{ASCII}*\z");
      if(result) {
         System.out.println("String approved");
      } else {
         System.out.println("Contains non-ASCII values");
      }
   }
}

Output1

Enter a string value:
hello how are you
String approved

Output2

Enter a string value:
whÿ do we fall
Contains non-ASCII values

Verifying each character

If you convert ASCII characters to integers all the results will be less than or equal to 127.

  • The charAt() method of the String class accepts an integer value and returns the character at specified index.

  • Using this method retrieve each character in the given String and verify whether they are greater than 127.

Example

 Live Demo

import java.util.Scanner;
public class OnlyASCII {
   public static void main(String[] args) {
      Scanner sc = new Scanner(System.in);
      System.out.println("Enter a string value: ");
      String input =sc.next();
      //Converting given string to character array
      char charArray[] = input.toCharArray();
      boolean result = true;
      for(int i = 0; i < input.length(); i++) {
         int test = (int)input.charAt(i);
         if (test<=127) {
            result = true;
         }else if (test >127){
            result = false;
         }
      }
      System.out.println(result);
      if(result) {
         System.out.println("String approved");
      }else {
         System.out.println("Contains non-ASCII values");
      }
   }
}

Output1

Enter a string value:
whÿ
false
Contains non-ASCII values

Output2

Enter a string value:
hello
true
String approved

Updated on: 14-Oct-2019

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements