给定一个字符串str ,任务是打印给定字符串的所有字谜,这些字符串构成了英语词典中存在的单词。
注意:为了使用字典单词,使用文本文件存储字典中的所有单词。
例子:
Input: str = “tac”
Output:
act
cat
Explanation:
The words can be formed from the given string “tac” are act, cat.
Input: str = “atrew”
Output:
tawer
water
wreat
Explanation:
The words can be formed from the given string “atrew” are “tawer”, “water”, “wreat”.
方法:这个想法是使用文件处理的概念和一个包含所有有意义的单词的文本文件(比如words.txt )。以下是步骤:
- 对给定的字符串排序。
- 使用文件处理ifstream打开words.txt文件以在 C++ 中读取文件为:
ifstream words(“words.txt”);
- For each word in the file words.txt sort the word and compare it with the given sorted string.
- If both the string matches in the above step then print the current word in the file words.txt.
- 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;
}
输出:
链接到文本文件:链接
如果您想与行业专家一起参加直播课程,请参阅Geeks Classes Live