简体   繁体   中英

find and compare characters in two strings

// if (var1.substr (0, 2) == alphaLetter[i]) 

This if is not legal. Is it possible somehow to check the first 3 characters in var1 are in alphaLetter ?

int main ()
{
    std::string const alphaLetter = "ABCDEFGHIJKLMNOPRSTVUYWQZX";

    std::string var1= "";
    std::cout << " Enter 6 characters: ";
    std::cin >> var1;
    for (int i = 0; i < alphaLetter.size (); i++)
    {
        for (int n = 0; n < alphaLetter.size(); n++)
        {
            if (var1.substr (0, 2) == alphaLetter[i])
            {
                std::cout << "True";
            }
        }
    }
}
if (var1.substr(0, 3).find_first_not_of(alphaLetter) == std::string::npos) {
  // The first three characters are all present in alphaLetter
}
if (var1.substr (0, 2) == alphaLetter[i])

That's illegal, because you try to compare std::string (with length 2) and char .

You can use find_first_not_of method ( docs ):

auto pos = var1.find_first_not_of(alphaLetter);
if (pos == std::string::npos ||  // means there's no letters not in alphaLetter
    pos >= 3)
{
    ...
}

On the other hand, if you need to find out if a char is in range A..Z you can check if it's code is in range ord(A)..ord(Z) :

auto firstThreeLetters = var1.substr(0, 3);
if (std::all_of(firstThreeLetters.begin(), firstThreeLetters.end(),
    [](char c) {
        return c >= 'A' && c <= 'Z';
    })
{
    ...
}

That's faster, because find_first_not_of iterates over alphaLetter for each letter of string at the worst case.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM