The idea is to have a String read and to verify that it does not contain any numeric characters. So something like "smith23" would not be acceptable.
To check whether a String contains only unicode letters or digits in Java, we use the isLetterOrDigit() method and charAt() method with decision-making statements. The isLetterOrDigit(char ch) method determines whether the specific character (Unicode ch) is either a letter or a digit.
To check if a string contains only alphabets, use the function isalpha() on the string. isalpha() returns boolean value. The return value is True if the string contains only alphabets and False if not.
To check if String contains only alphabets in Java, call matches() method on the string object and pass the regular expression "[a-zA-Z]+" that matches only if the characters in the given string is alphabets (uppercase or lowercase).
Method #1 : Using all() + isspace() + isalpha() This is one of the way in which this task can be performed. In this, we compare the string for all elements being alphabets or space only.
What do you want? Speed or simplicity? For speed, go for a loop based approach. For simplicity, go for a one liner RegEx based approach.
Speed
public boolean isAlpha(String name) { char[] chars = name.toCharArray(); for (char c : chars) { if(!Character.isLetter(c)) { return false; } } return true; }
Simplicity
public boolean isAlpha(String name) { return name.matches("[a-zA-Z]+"); }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With