![](/img/trans.png)
[英]How to check if a string contains all of the characters of another string?
[英]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;
}
这是一个演示。
std::set
。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.