Check if a string contains only alphabets in Java using Regex

Java 8Object Oriented ProgrammingProgramming

At first, convert the string into character array. Here, name is our string −

char[] ch = name.toCharArray();

Now, loop through and find whether the string contains only alphabets or not. Here, we are checking for not equal to a letter for every character in the string −

for (char c : ch) {
   if(!Character.isLetter(c)) {
      return false;
   }

Following is an example to check if a string contains only alphabets using Regex

Example

 Live Demo

public class Main {
   public static boolean checkAlphabet(String name) {
      char[] ch = name.toCharArray();
      for (char c : ch) {
         if(!Character.isLetter(c)) {
            return false;
         }
      }
      return true;
   }
   // Main method
   public static void main(String[] args) {
      String str1 = "Tom1";
      System.out.println("String1 = " + str1);
      System.out.println("Does String1 contains only alphabets? = " + checkAlphabet(str1));
      String str2 = "Tim";
      System.out.println("String2 = " + str2);
      System.out.println("Does String2 contains only alphabets? = " + checkAlphabet(str2));
   }
}

Output

String1 = Tom1
Does String1 contains only alphabets? = false
String2 = Tim
Does String2 contains only alphabets? = true
raja
Published on 20-Sep-2019 11:50:32
Advertisements