Check for specific characters used in a string?

In particular, I would like to know if only certain characters are used in a word. For example, the program will detect that only A B and are used in the input file C. I have it so far, but obviously this is an extremely brute force method.

Is there a more efficient way to do this? (I should also mention that this program does not work correctly, since I need to add many more conditions)

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();
}
+3
source share
2 answers

You can use regex as follows:

^[ABC]+$

To make sure the input contains only letters 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
0
source

. . Pattern. , , :

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

All Articles