How to verify that a string contains characters other than those specified. (in Java)

I have a program that asks the user to enter a three-character string. A string can only be a combination of a, b or c.

How to check if a string contains any characters other than those specified without a million conditional statements.

Pseudo example:

String s = "abq"

if (s.containsOtherCharacterThan(a,b,c))
    System.exit(-1)
+5
source share
5 answers

To search for characters that are not a, b, or c, use something like the following:

if(!s.matches("[abc]+"))
{
    System.out.println("The string you entered has some incorrect characters");
}
+8
source

You can use the regular expression and its character classes . Just call String#matches(String regex)on the line you want to check if it can fully match the regular expression.

if (!s.matches("[abc]+")) {//..

, , [ ], "abq" , q. , s a, b c. , false, if block.

+4

, .

public boolean containsOtherCharacter(String s, String a, String b, String c) {
    String[] st = s.split("");
    for(int x = 0; x < st.length; x++)
        if (st[x].compareTo(a) != 0 && st[x].compareTo(b) != 0 && st[x].compareTo(c) != 0)
            return true;
    return false;
}

, . , , HashMap, , - , .

+2

: - [abc]+.

+1

A way without regex would be to iterate over the string and check each character coming out if the character has a value other than a, b, or c. It is not possible to do this only with String.contains

+1
source

All Articles