Check if a string contains only the characters in another string

我们两清 提交于 2021-02-04 21:56:27

问题


I want to write a function that determines if all the letters of an inputted word are contained in another string of acceptable letters.

bool ContainsOnly(std::string inputtedWord, std::string acceptableLetters)
{
    // ... how do I write this?
}

Here's my testing framework:

bool Tester(std::string inputtedWord, std::string acceptableLetters)
{
    if (ContainsOnly(inputtedWord, acceptableLetters)) {
        std::cout << "Good!" << std::endl;
        return true;
    }
    else {
        std::cout << "No good!" << std::endl;
        return false;
    }
}

int main()
{
    std::string acceptableLetters;
    std::string inputtedWord;

    std::cout << "Please input the acceptable letters in your words: " << std::endl;
    std::cin >> acceptableLetters;

    while (inputtedWord != "STOP") 
    {
        std::cout << "Please input the word you would like to test: (type STOP to end testing): " << std::endl;
        std::cin >> inputtedWord;
        Tester(inputtedWord, acceptableLetters);
    }
    return 0;
}

I want the following output:

Please input the acceptable letters in your words: CODING

Please input the word you would like to test: (type STOP to end testing): COIN

Good!

Please input the word you would like to test: (type STOP to end testing): COP

No good!


回答1:


You can use find_first_not_of like this:

bool ContainsOnly(std::string inputtedWord, std::string acceptableLetters)
{
    return inputtedWord.find_first_not_of(acceptableLetters) == std::string::npos;
}

Here's a demo.




回答2:


  1. Put all the acceptable characters to std::set.
  2. Judge if all characters in the strings are in the set via std::all_of.
#include <set>
#include <algorithm>

bool ContainsOnly(std::string inputtedWord, std::string acceptableLetters)
{
     std::set<char> okSet(acceptableLetters.begin(), acceptableLetters.end());
     return std::all_of(inputtedWord.begin(), inputtedWord.end(),
                        [&okSet](char c) 
                        { 
                          return okSet.find(c) != okSet.end(); 
                        });
}


来源:https://stackoverflow.com/questions/64519529/check-if-a-string-contains-only-the-characters-in-another-string

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!