Check if the String contains only unicode letters and space 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)

where 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 to check whether a string contains Unicode Digits and Space in Java.

Example

public class Example {
   boolean check(String s) {
      int l=0; // counter for number of letters
      int sp=0; // counter for number of spaces
      if (s == null) // checks if the String is null {
         return false;
      }
      int len = s.length();
      for (int i = 0; i < len; i++) {
         if ((Character.isLetter(s.charAt(i)) == true)) {
            l++;
         }
         if(s.charAt(i) == ' ') {
            sp++;
         }
      }
      if(sp==0 || l==0 ) // even if one of them is zero then returns false
         return false;
      else
         return true;
   }
   public static void main(String [] args) {
      Example e = new Example();
      String s = "sid";
      String s1 = "y o y";
      System.out.println("String "+s+" has only unicode letters and spaces :"+e.check(s));
      System.out.println("String "+s1+" has only unicode letters and spaces: "+e.check(s1));
   }
}

Output

String s id has only unicode letters and spaces: false
String y o y has only unicode letters and spaces: true
raja
Published on 07-Jan-2019 11:12:35
Advertisements