Search code examples
c++strchr

Can Strchr function find numerous letters in a string in c++?


Diff FBullAndCow::EDifficulty(std::string diff) const
{
    if ((diff.length() > 1))
    {
        return Diff::Not_Number;
    }
    else if (!strchr(diff.c_str(), '3' || '4' || '5' || '6' || '7' || '8'))
    {
        return Diff::Not_Number;
    }
    return Diff::Ok;
}

Is it possible to find numerous characters in a string with strchr? I tried the method above, but it's not working. I suppose it's because strchr returns the occurrences of a character?

P.S:. I tried

    if ((!strchr(diff.c_str(), '3')) || (!strchr(diff.c_str(), '4')))

to use it this way too, though it was probably stupid. I'm a total rookie... I did try to look for a way for hours, but since I couldn't find anything, I'm here.

EDIT: It needs to return the number it finds. Sorry for leaving this out.


Solution

  • The direct answer is: no, you cannot check for multiple chars in strchr. That function just looks for one, specific character.

    If you need to search for all the numeric characters, since you're using a std::string (why are you aliasing this?), you can use find_first_of(). Or, more likely, find_first_not_of(), checking that diff.find_first_not_of("0123456789") == std::string::npos.

    However, even that's not a good solution - since presumably once you verify that it is numeric, you'll want the actual number. So it may be more direct to just use std::stoi() and verify that it didn't throw and consumed the whole string.