繁体   English   中英

检查一个字符串是否只包含另一个字符串中的字符

[英]Check if a string contains only the characters in another string

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

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

不好!

您可以像这样使用find_first_not_of

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

这是一个演示

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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