📜  自定义混乱文字游戏

📅  最后修改于: 2021-05-30 09:30:09             🧑  作者: Mango

在给定字符串str的情况下,任务是打印给定字符串的所有字谜,从而形成英语词典中存在的单词。

注意:要使用字典词,将使用一个文本文件存储字典中所有词。

例子:

方法:想法是使用文件处理的概念和包含所有有意义单词的文本文件(例如words.txt )。步骤如下:

  1. 对给定的字符串排序。
  2. 使用文件处理ifstream打开word.txt文件,以在C++中读取文件,如下所示:
  3. For each word in the file words.txt sort the word and compare it with the given sorted string.
  4. If both the string matches in the above step then print the current word in the file words.txt.
  5. Close the file after all the words has been checked.

下面是上述方法的实现:

C++
// C++ program for the above approach
  
#include 
using namespace std;
  
// Function that sorts the given string
// and transform a sorted string to uppercase
string sortString(string word)
{
    // Transformed to uppercase
    transform(word.begin(), word.end(),
              word.begin(), ::toupper);
  
    // Sort the words
    sort(word.begin(), word.end());
    return word;
}
  
// Function that finds the anagram of
// given string in the given text file
void jumbledString(string jumble)
{
    // Initialize strings
    string checkPerWord = "";
    string userEnteredAfterSorting;
  
    // Sort the string
    userEnteredAfterSorting
        = sortString(jumble);
  
    // Using filehandling ifstream
    // to read the file
    ifstream words("words.txt");
  
    // If file exist
    if (words) {
  
        // Check each and every word
        // of words.txt(dictionary)
        while (getline(words,
                       checkPerWord)) {
  
            string Ch
                = sortString(checkPerWord);
  
            // If words matches
            if (Ch
                == userEnteredAfterSorting) {
  
                // Print the word
                cout << checkPerWord
                     << endl;
            }
        }
  
        // Close the file
        words.close();
    }
}
  
// Driver Code
int main()
{
    // Given string str
    string string = "tac";
  
    // Function Call
    jumbledString(string);
  
    return 0;
}


输出:

链接到文本文件:链接

想要从精选的最佳视频中学习和练习问题,请查看有关从基础到高级C++的C++基础课程以及有关语言和STL的C++ STL课程。要完成从学习语言到DS Algo等的更多准备工作,请参阅“完整面试准备课程”