【问题标题】:Check if a string contains only the characters in another string检查一个字符串是否只包含另一个字符串中的字符
【发布时间】:2020-10-25 01:29:12
【问题描述】:

我想写一个函数来判断一个输入单词的所有字母是否都包含在另一个可接受的字母字符串中。

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

这是我的测试框架:

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;
}

我想要以下输出:

请在您的单词中输入可接受的字母:CODING

请输入您要测试的单词:(输入STOP结束测试):COIN

很好!

请输入您要测试的单词:(输入 STOP 结束测试):COP

不好!

【问题讨论】:

  • 这里有一个简单的方法来弄清楚如何做到这一点,它永远不会失败。只需拿出一张白纸。用简单的英语用简短的句子写下来,这是一个循序渐进的过程。完成后,call your rubber duck for an appointment。我们不会在 Stackoverflow 上为其他人编写代码。我们总是向您的橡皮鸭提出此类问题。在您的橡皮鸭批准您提出的行动计划后,只需将您写下的内容直接翻译成 C++。任务完成!

标签: c++ c++11 stdstring


【解决方案1】:

你可以像这样使用find_first_not_of

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

这是demo

【讨论】:

    【解决方案2】:
    1. 将所有可接受的字符放入std::set
    2. 通过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(); 
                            });
    }
    

    【讨论】:

    • 我编辑了问题以将逻辑放入函数而不是 if 语句中,因此我也更新了您的答案。希望没问题。
    猜你喜欢
    • 2013-03-13
    • 1970-01-01
    • 1970-01-01
    • 2021-05-06
    • 1970-01-01
    • 1970-01-01
    • 2014-04-14
    • 1970-01-01
    • 2023-03-31
    相关资源
    最近更新 更多