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
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
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
http://docs.oracle.com/javase/6/docs/api/java/util/regex/Pattern.html
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
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()) {
//...
}