Java检查字符串是否包含具有包含或等于方法的特定范围的某些字母

时间:2017-09-03 18:28:52

标签: java string contains letter

import.java.util.Scanner;

public class Test{
   public static void main(String[] args){
   Scanner sc = new Scanner(System.in)
   String operation = sc.nextLine();
   }
}

当我想看,如果字符串操作包含某些字母,我可以写f.ex。

    if(operation.contains("a") || operation.contains("b")){
        System.out.println("This is not a valid choice. Please retry!");
    }

但我想知道要写什么,如果字符串包含字母,例如从a到k。如果我用||写它每一次都没有效率。 编辑:我只允许使用方法contains和equals。

2 个答案:

答案 0 :(得分:3)

尝试使用正则表达式:

if (operation.matches(".*[a-k].*") {
    ...
}

替代方案:

boolean contains = false;
for (char charToCheck = 'a'; charToCheck <= 'k'; charToCheck++) {
    if (operation.indexOf(charToCheck) >= 0) {
        // found something
        contains = true;
        break;
    }
}

稍后更新

哦,indexOf()也不允许。使用嵌套循环的版本:

boolean found = false;
for (char ch : operation.toCharArray()) {
    for (ch charToCheck = 'a'; charToCheck <= 'k'; charToCheck++) {
        if (ch == charToCheck) {
            found = true;
            break;
        }
    }
    if (found) {
        break;
    }
}

答案 1 :(得分:-1)

char[] chars = operation.toCharArray();
for (int i = 0; i < chars.length; i++) {
    char val = chars[i];
    switch(val) {
        case a:
        case b:
        case c:
        case d:
        case e:
        case f:
        case g:
        case h:
        case i:
        case j:
        case k:
            System.out.println("This is not a valid choice. Please retry!");
            break;
     }
}