99

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.

blo0p3r
  • 6,790
  • 8
  • 49
  • 68
kodie hill
  • 1,007
  • 1
  • 8
  • 3
  • If you write an extension method for strings, the check can be built in. You could also use one that's already written such as the [Extensions.cs](https://www.nuget.org/packages/Extensions.cs) NuGet package that makes it as simple as: For example: "abcXYZ".IsAlphabetic() will return True whereas "abc123".IsAlphabetic() will return False. – Cornelius J. van Dyk Jan 20 '21 at 13:29

17 Answers17

157

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]+");
}
adarshr
  • 61,315
  • 23
  • 138
  • 167
  • 18
    I might be pendantic here, but "isLetter" is not the same as [a-zA-Z] – krosenvold Oct 15 '13 at 12:06
  • 5
    Keep 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 using `Character.isLetter(char)`. (See http://docs.oracle.com/javase/7/docs/api/java/lang/Character.html#supplementary) Instead, you would need to use a combination of `String.codePointAt()` and `Character.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
    Lambda approach would be even simpler. – IgorGanapolsky Mar 11 '16 at 17:11
  • 1
    @IgorGanapolsky requires API 24 or above. – Maihan Nijat Jun 27 '18 at 14:33
  • @MaihanNijat use RetroLambda – IgorGanapolsky Jun 27 '18 at 14:48
88

Java 8 lambda expressions. Both fast and simple.

boolean allLetters = someString.chars().allMatch(Character::isLetter);
Max Malysh
  • 29,384
  • 19
  • 111
  • 115
40

Or if you are using Apache Commons, [StringUtils.isAlpha()].

Ashish
  • 1,121
  • 2
  • 15
  • 25
Robby Pond
  • 73,164
  • 16
  • 126
  • 119
14

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

shalamus
  • 2,192
  • 1
  • 12
  • 8
6

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
Andris Leduskrasts
  • 1,210
  • 7
  • 16
iyas
  • 61
  • 1
  • 1
  • 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 06 '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 07 '15 at 10:29
5

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.

dzikoysk
  • 1,560
  • 1
  • 15
  • 27
mark_infinite
  • 383
  • 1
  • 7
  • 13
4
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.

LifesAway
  • 159
  • 1
  • 5
4

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
Pratiyush Kumar Singh
  • 1,977
  • 3
  • 19
  • 39
4

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;
}
Pravin Suthar
  • 1,403
  • 1
  • 14
  • 25
3
        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
        }
  • 4
    That's a more complicated version of the "Simplicity" thing @adarshr posted three years ago? – mabi Jun 07 '14 at 12:19
3

Try using regular expressions: String.matches

Brent Worden
  • 10,624
  • 7
  • 52
  • 57
1
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;
}
Joren
  • 3,068
  • 25
  • 44
Surender Singh
  • 688
  • 6
  • 9
  • 1
    This does only check the first char! So `A12341` would return `true`. -1 – jAC Jun 21 '17 at 18:56
  • @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
  • Yes, Thanks a lot – Surender Singh Jul 12 '17 at 10:32
1

Feels as if our need is to find whether the character are only alphabets. Here's how you can solve it-

Character.isAlphabetic(c) 

helps to check if the characters of the string are alphabets or not. where c is

char c = s.charAt(elementIndex);
Starwave
  • 2,352
  • 2
  • 23
  • 30
Anvita Shukla
  • 409
  • 7
  • 7
0

While there are many ways to skin this cat, I prefer to wrap such code into reusable extension methods that make it trivial to do going forward. When using extension methods, you can also avoid RegEx as it is slower than a direct character check. I like using the extensions in the Extensions.cs NuGet package. It makes this check as simple as:

  1. Add the https://www.nuget.org/packages/Extensions.cs package to your project.
  2. Add "using Extensions;" to the top of your code.
  3. "smith23".IsAlphabetic() will return False whereas "john smith".IsAlphabetic() will return True. By default the .IsAlphabetic() method ignores spaces, but it can also be overridden such that "john smith".IsAlphabetic(false) will return False since the space is not considered part of the alphabet.
  4. Every other check in the rest of the code is simply MyString.IsAlphabetic().
0

To allow only ASCII letters, the character class \p{Alpha} can be used. (This is equivalent to [\p{Lower}\p{Upper}] or [a-zA-Z].)

boolean allLettersASCII = str.matches("\\p{Alpha}*");

For allowing all Unicode letters, use the character class \p{L} (or equivalently, \p{IsL}).

boolean allLettersUnicode = str.matches("\\p{L}*");

See the Pattern documentation.

Unmitigated
  • 76,500
  • 11
  • 62
  • 80
0

I found an easy of way of checking a string whether all its digit is letter or not.

public static boolean isStringLetter(String input) {

    boolean b = false;
    for (int id = 0; id < input.length(); id++) {
        if ('a' <= input.charAt(id) && input.charAt(id) <= 'z') {
            b = true;
        } else if ('A' <= input.charAt(id) && input.charAt(id) <= 'Z') {
            b = true;
        } else {
            b = false;
        }
    }
    return b;
}

I hope it could help anyone who is looking for such method.

-1

Use StringUtils.isAlpha() method and it will make your life simple.

Shyadav
  • 1
  • 2
  • 1
    this is a copy of another solution to the question. Please consider updating it to do something different. – Frayal Jan 03 '19 at 14:53