Check if a string contains only alphabets in Java using ASCII values


Let’s say we have set out inut string in myStr variable. Now loop through until the length of string and check for alphabets with ASCII values −

for (int i = 0; i < myStr.length(); i++) {
   char c = myStr.charAt(i);
   if (!(c >= 'A' && c <= 'Z') && !(c >= 'a' && c <= 'z')) {
      return false;
   }
   return true;
}

Following is an example to check if a string contains only alphabets in Java using ASCII values;

Example

class Main {
   public static boolean checkAlphabet(String myStr) {
      for (int i = 0; i < myStr.length(); i++) {
         char c = myStr.charAt(i);
         if (!(c >= 'A' && c <= 'Z') && !(c >= 'a' && c <= 'z')) {
            return false;
         }
      }
      return true;
   }
   public static void main(String[] args) {
      String str1 = "Tom1";
      System.out.println("String1 = " + str1);
      System.out.println("Is String1 contains only alphabets? = " + checkAlphabet(str1));
      String str2 = "Tim";
      System.out.println("String2 = " + str2);
      System.out.println("Is String2 contains only alphabets? = " + checkAlphabet(str2));
   }
}

Output

String1 = Tom1
Is String1 contains only alphabets? = false
String2 = Tim
Is String2 contains only alphabets? = true

Updated on: 20-Sep-2019

388 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements