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.
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]+");
}
-
13I might be pendantic here, but "isLetter" is not the same as [a-zA-Z] – krosenvold Oct 15 '13 at 12:06
-
2Keep in mind that in Java, a
char[]
will be encoded as UTF-16. This means a multi-character glyph (where both chars are in the surrogate ranges) will fail to be recognized as a letter when examined individually usingCharacter.isLetter(char)
. (See docs.oracle.com/javase/7/docs/api/java/lang/…) Instead, you would need to use a combination ofString.codePointAt()
andCharacter.isLetter(int)
. Of course, if you know for sure that the characters in your string are in the ASCII or extended single-char-encoded ranges, then the above answer will work. – Ionoclast Brigham Dec 29 '14 at 18:38 -
1
-
-
Java 8 lambda expressions. Both fast and simple.
boolean allLetters = someString.chars().allMatch(Character::isLetter);
-
3
-
4
I used this regex expression (".*[a-zA-Z]+.*")
. With if not
statement it will avoid all expressions that have a letter before, at the end or between any type of other character.
String strWithLetters = "123AZ456";
if(! Pattern.matches(".*[a-zA-Z]+.*", str1))
return true;
else return false
-
the
.*
at the start and end of it is not correct. As they can be any length and include digits,123smith123
would be a valid name. Something like ``^[a-zA-Z]+$` would work though, if it's only the single word in the string. – Andris Leduskrasts Jul 6 '15 at 10:08 -
I guess I gave a wrong answer. You are right. My code checks if the String does not have any letter. – iyas Jul 7 '15 at 10:29
A quick way to do it is by:
public boolean isStringAlpha(String aString) {
int charCount = 0;
String alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
if (aString.length() == 0) {
return false; //zero length string ain't alpha
}
for (int i = 0; i < aString.length(); i++) {
for (int j = 0; j < alphabet.length(); j++) {
if (aString.substring(i, i + 1).equals(alphabet.substring(j, j + 1))
|| aString.substring(i, i + 1).equals(alphabet.substring(j, j + 1).toLowerCase())) {
charCount++;
}
}
if (charCount != (i + 1)) {
System.out.println("\n**Invalid input! Enter alpha values**\n");
return false;
}
}
return true;
}
Because you don't have to run the whole aString
to check if it isn't an alpha String.
First import Pattern :
import java.util.regex.Pattern;
Then use this simple code:
String s = "smith23";
if (Pattern.matches("[a-zA-Z]+",s)) {
// Do something
System.out.println("Yes, string contains letters only");
}else{
System.out.println("Nope, Other characters detected");
}
This will output:
Nope, Other characters detected
Faster way is below. Considering letters are only a-z,A-Z.
public static void main( String[] args ){
System.out.println(bestWay("azAZpratiyushkumarsinghjdnfkjsaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"));
System.out.println(isAlpha("azAZpratiyushkumarsinghjdnfkjsaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"));
System.out.println(bestWay("azAZpratiyushkumarsinghjdnfkjsaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa1aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"));
System.out.println(isAlpha("azAZpratiyushkumarsinghjdnfkjsaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa1aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"));
}
public static boolean bettertWay(String name) {
char[] chars = name.toCharArray();
long startTimeOne = System.nanoTime();
for(char c : chars){
if(!(c>=65 && c<=90)&&!(c>=97 && c<=122) ){
System.out.println(System.nanoTime() - startTimeOne);
return false;
}
}
System.out.println(System.nanoTime() - startTimeOne);
return true;
}
public static boolean isAlpha(String name) {
char[] chars = name.toCharArray();
long startTimeOne = System.nanoTime();
for (char c : chars) {
if(!Character.isLetter(c)) {
System.out.println(System.nanoTime() - startTimeOne);
return false;
}
}
System.out.println(System.nanoTime() - startTimeOne);
return true;
}
Runtime is calculated in nano seconds. It may vary system to system.
5748//bettertWay without numbers
true
89493 //isAlpha without numbers
true
3284 //bettertWay with numbers
false
22989 //isAlpha with numbers
false
Check this,i guess this is help you because it's work in my project so once you check this code
if(! Pattern.matches(".*[a-zA-Z]+.*[a-zA-Z]", str1))
{
String not contain only character;
}
else
{
String contain only character;
}
private boolean isOnlyLetters(String s){
char c=' ';
boolean isGood=false, safe=isGood;
int failCount=0;
for(int i=0;i<s.length();i++){
c = s.charAt(i);
if(Character.isLetter(c))
isGood=true;
else{
isGood=false;
failCount+=1;
}
}
if(failCount==0 && s.length()>0)
safe=true;
else
safe=false;
return safe;
}
I know it's a bit crowded. I was using it with my program and felt the desire to share it with people. It can tell if any character in a string is not a letter or not. Use it if you want something easy to clarify and look back on.
String expression = "^[a-zA-Z]*$";
CharSequence inputStr = str;
Pattern pattern = Pattern.compile(expression);
Matcher matcher = pattern.matcher(inputStr);
if(matcher.matches())
{
//if pattern matches
}
else
{
//if pattern does not matches
}
-
4That's a more complicated version of the "Simplicity" thing @adarshr posted three years ago? – mabi Jun 7 '14 at 12:19
public boolean isAlpha(String name)
{
String s=name.toLowerCase();
for(int i=0; i<s.length();i++)
{
if((s.charAt(i)>='a' && s.charAt(i)<='z'))
{
continue;
}
else
{
return false;
}
}
return true;
}
-
1
-
@JanesAbouChleih, yes you were right. I have edited it. Please check now – Surender Singh Jul 12 '17 at 10:10
-
I removed my downvote. This answer is correct now, but can be easily be enhanced by removing the
continue
block.public boolean isAlpha(String name) { String s = name.toLowerCase(); for (int i = 0; i < s.length(); i++) { if ((s.charAt(i) < 'a' || s.charAt(i) > 'z')) { return false; } } return true; }
– jAC Jul 12 '17 at 10:20 -
Use StringUtils.isAlpha() method and it will make your life simple.
-
1this is a copy of another solution to the question. Please consider updating it to do something different. – Alexis Jan 3 at 14:53
Solution: I prefer to use a simple loop.
public static boolean isAlpha(String s) {
if (s == null || s.length() == 0) {
return false;
}
char[] chars = s.toCharArray();
for (int index = 0; index < chars.length; index++) {
int codePoint = Character.codePointAt(chars, index);
if (!Character.isLetter(codePoint)) {
return false;
}
}
return true;
}