Check if the String contains only unicode letters, digits or space in Java


To check if a given String contains only unicode letters, digits or space, we use the isLetterOrDigit() and charAt() methods with decision making statements.

The isLetterOrDigit(char ch) method determines whether the specific character (Unicode ch) is either a letter or a digit. It returns a boolean value, either true or false.

Declaration −The java.lang.Character.isLetter() method is declared as follows −

public static boolean isLetter(char ch)

The charAt() method returns a character value at a given index. It belongs to the String class in Java. The index must be between 0 to length()-1.

Declaration −The java.lang.String.charAt() method is declared as follows −

public char charAt(int index)

Let us see a program in Java which checks if a String contains only Unicode letter, digits or space.

Example

 Live Demo

public class Example {
   boolean check(String s) {
      if (s == null) // checks if the String is null {
         return false;
      }
      int len = s.length();
      for (int i = 0; i < len; i++) {
         // checks whether the character is neither a letter nor a digit and not even a space
         // if it is neither a letter nor a digit and not even a space then it will return false
         if ((Character.isLetterOrDigit(s.charAt(i)) == false) && s.charAt(i)!=' ') {
            return false;
         }
      }
      return true;
   }
   public static void main(String [] args) {
      Example e = new Example();
      String s = "@ # @"; // returns false due to special character presence
      String s1 = "134s"; // returns true
      String s2 = "1 0d"; // returns true
      String s3 = "1 x"; // returns true
      System.out.println("String "+s+" has only unicode letters,digits or space : "+e.check(s));
      System.out.println("String "+s1+" has only unicode letters,digits or space: "+e.check(s1));
      System.out.println("String "+s2+" has only unicode letters,digits or space: "+e.check(s2));
      System.out.println("String "+s3+" has only unicode letters,digits or space : "+e.check(s3));
   }
}

Output

String @ # @ has only unicode letters,digits or space : false
String 134s has only unicode letters,digits or space: true
String 1 0d has only unicode letters,digits or space: true
String 1 x has only unicode letters,digits or space : true

Updated on: 25-Jun-2020

697 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements