Check if the String contains only unicode letters in Java

Java 8Object Oriented ProgrammingProgramming

In order to check if a String has only Unicode letters in Java, we use the isDigit() and charAt() methods with decision-making statements.

The isLetter(int codePoint) method determines whether the specific character (Unicode codePoint) is a letter. It returns a boolean value, either true or false.

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

public static boolean isLetter(int codePoint)

Here, the parameter codePoint represents the character to be checked.

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 to check if a String has only Unicode Letters.

Example

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 not a letter
         // if it is not a letter ,it will return false
         if ((Character.isLetter(s.charAt(i)) == false)) {
            return false;
         }
      }
      return true;
   }
   public static void main(String [] args) {
      Example e = new Example();
      String s = "@asd"; // returns false due to special character presence
      String s1 = "134s"; // returns false due to presence of digits
      String s2 = "abcd"; // returns true
      String s3= "g c1"; // returns false due to space and digits
      System.out.println("String "+s+" has only unicode letters : "+e.check(s));
      System.out.println("String "+s1+" has only unicode letters : "+e.check(s1));
      System.out.println("String "+s2+" has only unicode letters : "+e.check(s2));
      System.out.println("String "+s3+" has only unicode letters : "+e.check(s3));
   }
}

Output

String @asd has only unicode letters : false
String 134s has only unicode letters : false
String abcd has only unicode letters : true
String g c1 has only unicode letters : false
raja
Published on 07-Jan-2019 16:35:10
Advertisements