Daniel
Daniel

Reputation: 541

Comparing with more than one char in C++

Say I have an input that is stored in a char c, and in a conditional I need to check whether it is either of two different characters, for example 'n' and 'N'. It's obvious that I can make a conditional with a logical OR operator:

if(c == 'n' || c == 'N')
...

However, if there are significantly more than just two conditions, than that will require significantly more logical operators to be used, and it will become tedious to write, look at, and edit. Is there a way to condense this process? To make it look like something along the lines of this:

if(c == '[N][n]')
...

Does anything of the sort exist?

Upvotes: 2

Views: 1789

Answers (3)

Christian Hackl
Christian Hackl

Reputation: 27528

A low-tech solution would be to use a switch statement instead. Reading and editing may turn out to be much easier with case labels if you have a lot of matching characters.

bool matches(char c)
{
    switch (c)
    {
        case 'n':
        case 'N':
        case 'a':
        case 'b':
        case 'c':
        return true;
    }
    return false;
}

A more advanced solution would be to store the characters in a container. std::set would be an option:

bool matches(char c)
{
    // note: might want to use static storage for `chars`
    std::set<char> const chars =
    {
        'n',
        'N',
        'a',
        'b',
        'c',
    };
    return chars.find(c) != end(chars);
}

std::string allows for a more condensed form, which may be good or bad as far as readability and maintainability is concerned:

bool matches(char c)
{
    // note: might want to use static storage for `chars`
    std::string const chars = "nNabc";
    return chars.find(c) != std::string::npos;
}

Note that different containers have different algorithmic complexity characteristics, which may be relevant if a function like match should actually turn out to be a performance bottleneck.

Upvotes: 5

Raindrop7
Raindrop7

Reputation: 3911

You can use to_upper or to_lower APIs if your scanning is not case sensitive this way:

char c = 'n';
if( static_cast<unsigned char>('N') == std::toupper(static_cast<unsigned char>(c)) )
    // do something

Or:

char c = 'n';
if( static_cast<unsigned char>('n') == std::tolower(static_cast<unsigned char>(c)) )
    // Do something

Upvotes: 1

scohe001
scohe001

Reputation: 15446

You can make a string of your matching characters and see if the character in question exists in the string:

char c;
std::string good_chars = "nNyYq";
if(good_chars.find(c) != std::string::npos) {
    std::cout << "it's good!";
}

Upvotes: 9

Related Questions