在文本文件中存储的单词与字符串的排列进行比较

3

我想找出用户输入的字符串的任何排列是否是一个包含少量单词的文本文件中的有效单词。

在输入字符串后,什么都没有发生! "if"语句有什么问题?如果我编写了一个else语句并且被执行,这意味着控制从未到达if,即使我输入了列表.txt中存在的单词

我该尝试什么来解决这个问题?

//check if any permutation of a user inputted word are in a pre defined text file

    #include <iostream>
    #include <fstream>
    #include <vector>

    using namespace std;

    int main(){
        cout<<"Enter a word to check for the presence of any
        << of its permutation in a file \n"; 
        string word; 
        cin>>word; 
        sort(word.begin(), word.end()); 
        vector<string> str; 
        do str.push_back(word);
        while( next_permutation(word.begin(),word.end()) );                  

        ifstream readFile("list.txt");
        string line;
        while(readFile>>line){
              for (int i = 0; i < str.size(); ++i){
                  if(line==str[i]){
                     cout << "found " << str[i] << endl;
                     break;
                  }
              }
        }
        system("pause");
        return EXIT_SUCCESS;
    }

程序完全没问题,我在运行时输入的是小写字母,而我的文本文件中的字符串是大写字母...浪费了几个小时,终于发现了这个错误...虽然如此,还是感谢大家纠正了代码中之前的缺陷和低效性。 - user1776433
3个回答

1

除非你的字典特别大(太大以至于无法全部存储在内存中),否则我建议从字典中读取一个单词,创建一个副本并对副本中的字母进行排序,然后将其添加到一对已排序/原始单词的向量中。当你读完所有单词后,按照已排序的单词顺序对向量进行排序。

当你想要检查字典是否包含一个(排列后的)单词时,请对该单词进行排序,然后使用std::equal_range在你的向量上查找所有匹配的单词。


1

您不需要进行任何排列组合。

您只需对字典中每个单词的字符进行排序,并与用户输入字符串中排序后的字符进行比较。它们可能匹配多个单词。您可以将字典存储为一对。我会做一次这样的操作并将其存储以供以后使用。例如:

addpy paddy
orst sort
cet etc

如果您按第一个(排序后的)单词对字典对进行排序,就可以使用二分搜索快速查找已排序的用户字符串,然后向两个方向查找其他匹配的单词。


0

1) 你应该将要搜索的字符串存储在一个向量中。

vector<string> words_to_search;
sort(word.begin(), word.end()); 
do 
   words_to_search.push_back(word);
while (next_permutation(word.begin(), word.end()));

然后你可以像这样循环遍历它们
for (vector<string>::iterator i = words_to_search.begin();
     i != words_to_search.end(); ++i)
{
    string search_word = *i;
    // search for search_word
    ...
}

2) 要比较您的字符串,只需使用 ==

if (line == search)

你可能需要先从 line 中删除前导和尾随的空格。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接