Tell if string contains a-z chars [duplicate]

泪湿孤枕 提交于 2019-12-05 17:51:32

问题


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


回答1:


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




回答2:


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 



回答3:


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.




回答4:


Try this

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


来源:https://stackoverflow.com/questions/24086968/tell-if-string-contains-a-z-chars

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!