How can a String be validated (for alphabets) in java?


To validate a string for alphabets you can either compare each character in the String with the characters in the English alphabet (both cases) or, use regular expressions.

Example1

The following program accepts a string value (name) from the user and finds out whether given string is a proper name by comparing each character in it with the characters in the English alphabet.

 Live Demo

import java.util.Scanner;
public class ValidatingString {
   public static void main(String args[]) {
      Scanner sc = new Scanner(System.in);
      System.out.println("Enter your name: ");
      String str = sc.next();
      boolean flag = true;
      for (int i = 0; i < str.length(); i++) {
         char ch = str.charAt(i);
         if (!(ch >= 'a' && ch <= 'z'|| ch >= 'A' && ch <= 'Z')) {
            flag = false;
         }
      }
      if(flag)
         System.out.println("Given string is a proper name.");
      else
         System.out.println("Given string is a proper string is not a proper name.");
   }
}

Output1

Enter your name:
krishna45
Given string is a proper string is not a proper name.

Output2

Enter your name:
kasyap
Given string is a proper name.

Example2

The following program accepts a string value (name) from the user and finds out whether the given string is a proper name, using a regular expression.

 Live Demo

import java.util.Scanner;
public class ValidatingString2 {
   public static void main(String args[]) {
      Scanner sc = new Scanner(System.in);
      System.out.println("Enter your name: ");
      String str = sc.next();
      if((!str.equals(null))&&str.matches("^[a-zA-Z]*$"))
         System.out.println("Given string is a proper name.");
      else
         System.out.println("Given string is a proper string is not a proper name.");
   }
}

Output1

Enter your name:
krishna45
Given string is a proper string is not a proper name.

Output2

Enter your name:
kasyap
Given string is a proper name.
raja
Published on 11-Oct-2019 10:36:41
Advertisements