检查字符串中是否使用特定字符?

3

具体来说,我想知道一个单词中是否仅仅使用了特定的字符。例如,程序将检测输入中是否仅仅使用了ABC。目前,我已经实现了这一点,但显然这是一种非常暴力的方法。

有更高效的方法吗?(我还应该提到,这个程序不能正常工作,因为我需要添加许多其他条件)

public static void main(String[] args) {
    Scanner in = new Scanner(System.in);

    String str = in.nextLine();

    if(str.contains("I") && str.contains("O") && str.contains("S") && str.contains("H") && str.contains("Z") && str.contains("X") && str.contains("N")){
        System.out.println("YES");
    }else if(str.contains("I") && str.contains("O") && str.contains("S") && str.contains("H") && str.contains("Z") && str.contains("X")){
        System.out.println("YES");
    }else if(str.contains("I") && str.contains("O") && str.contains("S") && str.contains("H") && str.contains("Z")){
        System.out.println("YES");
    }else if(str.contains("I") && str.contains("O") && str.contains("S") && str.contains("H")){
        System.out.println("YES");
    }else if(str.contains("I") && str.contains("O") && str.contains("S")){
        System.out.println("YES");
    }else if(str.contains("I") && str.contains("O")){
        System.out.println("YES");
    }else if(str.contains("I")){
        System.out.println("YES");
    }else{
        System.out.println("NO");
    }

    in.close();
}

你是指什么意思?“如果一个单词只使用了特定的字符”?你指的是哪个单词? - user557597
仅在字符串中使用指定字符。例如,我想检查字符串中是否仅使用 ABC。输入将是 CAB,输出将是 YES - user3315035
2个回答

5

你需要使用正则表达式来实现。请参见Pattern。或者,如果想要保持简单,你可以这样检测:

if( str.matches( "[ABC]+" ) ) {
    System.out.println("YES");
}

谢谢,你知道一个简洁的正则表达式语法库吗? - user3315035
1
我总是使用引用的 Pattern-javadoc。 - tangens

0
你可以使用类似这样的正则表达式:
^[ABC]+$

为了确保输入只包含字母 A OR B OR C

^ assert position at start of the string
[ABC]+ match a single character present in the list below
Quantifier: Between one and unlimited times, as many times as possible
[ABC] a single character in the list (A or B or C) literally (case sensitive)
$ assert position at end of the string

你能解释一下 $^ 的作用吗?我已经实现了你的代码,它完美地运行了,但是 ^$ 是做什么用的呢?从 tangens 的回答中可以看出,它们似乎不是必需的? - user3315035
^$被称为锚点,它们分别用于表示行的开头和结尾。在matches方法中,它们并不是必需的,因为Java API会默认添加。然而,为了编写一个良好的正则表达式(避免匹配到意外的结果),我建议使用它们。 - anubhava
2
@user3315035 ^ 匹配行开头,$ 匹配行结尾。你不需要它们,因为 matches 方法已经检查整个字符串是否匹配正则表达式。 - BackSlash

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接