首页 > 解决方案 > 如何检查向量中的 2 个子词是否与用户输入的字符串匹配?

问题描述

  1. 我正在做一个项目,在这个项目中,我从一个文本文件中遍历了数百个单词的列表。该文件名为 words.txt

  2. 我要求用户输入一个单词,然后从给定的单词中,找到所有长度大于 2 个字符并由用户指定单词中的字母组成的“不区分大小写”子单词。

  3. 例如:如果用户输入“Winter”这个词,它会有“win”、“int”、“wit”、“wire”、“rent”、“tin”、“twin”、“new”等子词“,。所有这些单词都包含在文本文件中(它非常大)。

  4. 我知道有一种方法可以检查单词是否匹配,但如果长度大于两个字符,我特别需要它来工作

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)
{
  
  

}


}

标签: c++stringloopsvectorsubstring

解决方案


一种非常简单有效的解决方案是将您的单词转换为字母计数数组(在此之前将它们更改为小写)。它可以是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"

推荐阅读