Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if String contains only letters

Tags:

java

string

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.

like image 378
kodie hill Avatar asked Mar 08 '11 21:03

kodie hill


People also ask

How can you check a string can only have alphabets and not digits?

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.

How do I check if a string contains only letters in Python?

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.

How do you check whether a string contains all alphabets in Java?

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).

How do you check if a string contains only alphabets and spaces in Python?

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.


1 Answers

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]+"); } 
like image 58
adarshr Avatar answered Sep 24 '22 10:09

adarshr