简体   繁体   English

检查字符串是否只包含字母

[英]Check if String contains only letters

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.所以像“smith23”这样的东西是不可接受的。

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]+");
}

Java 8 lambda expressions. Java 8 lambda 表达式。 Both fast and simple.既快速又简单。

boolean allLetters = someString.chars().allMatch(Character::isLetter);

或者,如果您使用的是 Apache Commons,请使用[StringUtils.isAlpha()]

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不,检测到其他字符

I used this regex expression (".*[a-zA-Z]+.*") .我使用了这个正则表达式(".*[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.使用if not语句,它将避免在任何类型的其他字符之前、末尾或之间有字母的所有表达式。

String strWithLetters = "123AZ456";
if(! Pattern.matches(".*[a-zA-Z]+.*", str1))
 return true;
else return false

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 .因为您不必运行整个aString来检查它是否不是alpha String

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.如果您想要一些易于澄清和回顾的内容,请使用它。

Faster way is below.更快的方法如下。 Considering letters are only az,AZ.考虑字母只有az,AZ。

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;
}
        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
        }

尝试使用正则表达式: String.matches

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;
}

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.使用扩展方法时,您还可以避免使用 RegEx,因为它比直接字符检查慢。 I like using the extensions in the Extensions.cs NuGet package.我喜欢使用 Extensions.cs NuGet 包中的扩展。 It makes this check as simple as:它使这项检查变得如此简单:

  1. Add the https://www.nuget.org/packages/Extensions.cs package to your project.https://www.nuget.org/packages/Extensions.cs包添加到您的项目中。
  2. Add " using Extensions; " to the top of your code.将“ using Extensions; ”添加到代码的顶部。
  3. "smith23".IsAlphabetic() will return False whereas "john smith".IsAlphabetic() will return True. "smith23".IsAlphabetic()将返回 False 而"john smith".IsAlphabetic()将返回 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.默认情况下, .IsAlphabetic()方法忽略空格,但它也可以被覆盖,这样"john smith".IsAlphabetic(false)将返回 False,因为空格不被视为字母表的一部分。
  4. Every other check in the rest of the code is simply MyString.IsAlphabetic() .其余代码中的所有其他检查都只是MyString.IsAlphabetic()

Feels as if our need is to find whether the character are only alphabets.感觉好像我们需要的是找出字符是否只是字母。 Here's how you can solve it-这是你如何解决它 -

Character.isAlphabet(int(c)) 

helps to check if the characters of the string are alphabets or not.有助于检查字符串的字符是否为字母。 where c is其中 c 是

s.charAt(elementIndex)

To allow only ASCII letters, the character class \\p{Alpha} can be used.要仅允许 ASCII 字母,可以使用字符类\\p{Alpha} (This is equivalent to [\\p{Lower}\\p{Upper}] or [a-zA-Z] .) (这相当于[\\p{Lower}\\p{Upper}][a-zA-Z] 。)

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

For allowing all Unicode letters, use the character class \\p{L} (or equivalently, \\p{IsL} ).要允许所有 Unicode 字母,请使用字符类\\p{L} (或等效的\\p{IsL} )。

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

See the Pattern documentation .请参阅Pattern文档

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.我希望它可以帮助任何正在寻找这种方法的人。

使用 StringUtils.isAlpha() 方法,它会让你的生活变得简单。

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;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM