Tell If String Contains a-Z Chars [Duplicate]

I very new to programming. I want to check if a string s contains a-z characters. I use:

if(s.contains("a") || s.contains("b") || ... {
}

but is there any way for this to be done in shorter code? Thanks a lot

3

You can use regular expressions

// to emulate contains, [a-z] will fail on more than one character, 
// so you must add .* on both sides.
if (s.matches(".*[a-z].*")) { 
    // Do something
}

this will check if the string contains at least one character a-z

to check if all characters are a-z use:

if ( ! s.matches(".*[^a-z].*") ) { 
    // Do something
}

for more information on regular expressions in java

1

In addition to regular expressions, and assuming you actually want to know if the String doesn't contain only characters, you can use Character.isLetter(char) -

boolean hasNonLetters = false;
for (char ch : s.toCharArray()) {
  if (!Character.isLetter(ch)) {
    hasNonLetters = true;
    break;
  }
}
// hasNonLetters is true only if the String contains something that isn't a letter -

From the Javadoc for Character.isLetter(char),

A character is considered to be a letter if its general category type, provided by Character.getType(ch), is any of the following:

UPPERCASE_LETTER
LOWERCASE_LETTER
TITLECASE_LETTER
MODIFIER_LETTER
OTHER_LETTER 
1

Use Regular Expressions. The Pattern.matches() method can do this easily. For example:

Pattern.matches("[a-z]", "TESTING STRING a");

If you need to check a great number of string this class can be compiled internally to improve performance.

Try this

Pattern p = Pattern.compile("[a-z]");
if (p.matcher(stringToMatch).find()) {
    //...
}
Chloe Bennett

Chloe Bennett

Culture, Media & Entertainment Columnist

Chloe Bennett explores the intersection of pop culture, streaming entertainment, digital trends, and contemporary lifestyle. Her weekly commentary reaches thousands of culture enthusiasts.

Share this article
Twitter Facebook Pinterest