c++ - 如何检查向量中的 2 个子词是否与用户输入的字符串匹配?
问题描述
我正在做一个项目,在这个项目中,我从一个文本文件中遍历了数百个单词的列表。该文件名为 words.txt
我要求用户输入一个单词,然后从给定的单词中,找到所有长度大于 2 个字符并由用户指定单词中的字母组成的“不区分大小写”子单词。
例如:如果用户输入“Winter”这个词,它会有“win”、“int”、“wit”、“wire”、“rent”、“tin”、“twin”、“new”等子词“,。所有这些单词都包含在文本文件中(它非常大)。
我知道有一种方法可以检查单词是否匹配,但如果长度大于两个字符,我特别需要它来工作
void subWord()
{
// user inputted word init
std::string userInputWord = {};
//input file stream object
std::ifstream file("words.txt");
// this vector will hold the list of words inputted from the while loop
std::vector<std::string> words;
std::string input;
// this loop continues as long as the read is successful and there is no more words to read
while(file >> input)
{
words.push_back(input);
}
std::cout << "Please enter a word: " << std::endl;
std::cin >> userInputWord;
// counter to keep track of times 2 characters match
int counter = 0;
// I know this how I would iterate over the list of words but then I need a way to check for two matching substrings
for (std::string word : words)
{
}
}
解决方案
一种非常简单有效的解决方案是将您的单词转换为字母计数数组(在此之前将它们更改为小写)。它可以是std::map<char,int>
or std::unordered_map<char,int>
(std::array<int,26>
其中索引 0 代表'a'
、 1 -'b'
等等)。然后,当且仅当来自文件的单词中每个字母的计数小于或等于用户输入中相同字母的计数时,文件中的单词才是您输入的子词。
例如单词“winter”将表示为:
'w' - 1, 'i' - 1, 'n' - 1, 't' - 1, 'e' - 1, 'r' - 1
所以
"int" which is 'i' - 1, 'n' - 1, 't' - 1 is a subword
但
"war" which is 'w' - 1, 'a' - 1, 'r' - 1 is not, because count of 'a' is 0 in "winter"
推荐阅读
- python - 使用 webargs 验证 AWS lambda 中的查询字符串参数和请求正文
- python - 返回所有参数总和的函数
- .htaccess - 暂停站点地图文件的尾部斜杠规则
- c# - 通过 C# 从市场映像中提升 Azure VM
- django - Django-tables2 为列标题指定 verbose_name 无效
- java - 使用应用程序属性文件在本机查询中选择表名?
- docker - FFmpeg 使用 -loop 标志的意外行为
- swift - Swift:将 SwiftUI 元素添加到 UIKit 项目:无法正确应用约束
- performance - System.Data.SQLite 版本 1.0.74 和最新的 1.0.113 之间有什么变化?
- excel - 如何在python中计数,并直接在数据框中创建列(与多列分组)