c++ - 如何从文本文件中获取长度为 9 的单词?

标签 c++ c++11

我想知道如何遍历一个文本文件并获取该文本文件中长度为 9 的所有单词,然后选择其中任何一个单词并随机化这些字母。

book = readWordsFile("misc/word.txt");
std::vector<std::string> text;
for(int i = 0; i<book.size();i++){
if(book[i] == 9) {

return book[i];
}
}

最佳答案

假设您有一个文件 words.txt,这是一个很大的长单词文件,用逗号分隔,例如流行的 MOOC 类(class) here 中的文件。 : 你可以这样做:

#include <iostream>
#include <fstream>
#include <vector>
#include <algorithm> // random_shuffle
#include <cstdlib> // rand()
using namespace std;

int main() {
    // init rand function
    srand(time(NULL));

    string dictionaryPath = "words.txt"; 
    ifstream ifs(dictionaryPath);
    vector<string> allNineLetterWords;
    char c;
    string word;
    // read words.txt and save 9 letter words into list
    while (ifs.get(c))
    {
        // seperate words by ,
        if (c == ',') {
            // store 9 letter words
            if (word.size() == 9) {
                allNineLetterWords.push_back(word);
            }
            word = "";
        } else {
            word += c;
        }
    }
    ifs.close();

    // randomize
    int randomIndex = rand() % allNineLetterWords.size();
    string originalWord = allNineLetterWords.at(randomIndex);
    string scrambledWord;
    vector<int> indices = {0, 1, 2, 3, 4, 5, 6, 7, 8};
    std::random_shuffle(indices.begin(), indices.end());
    for ( int i = 0 ; i < 9; i++) {
        int randomIndex = indices.at(i);
        scrambledWord += originalWord.at(randomIndex);
    }
    // print original and scrambled word
    cout << originalWord << ", " << scrambledWord << endl;

    return 0;
}

输出:

actuators, crsaotaut

unzipping, piungzinp

mobilizes, imilsezob

编辑:

如果您的目标是制作类似于倒计时字母和数字Des chiffres et des lettres 等节目的文字谜题/难题,如果您只选择 9 个字母的单词,即 4 个字母和 5 个字母的单词的组合,那就更有趣了。

类似这样的事情:

vector<string> findWords(string dictionaryPath, int length) {
    ifstream ifs(dictionaryPath);
    vector<string> allLengthNWords;
    char c;
    string word;
    // read words.txt and save 9 letter words into list
    while (ifs.get(c))
    {
        // seperate words by ,
        if (c == ',') {
            // store 9 letter words
            if (word.size() == length) {
                allLengthNWords.push_back(word);
            }
            word = "";
        } else {
            word += c;
        }
    }
    ifs.close();
    return allLengthNWords;
}

bool twoWordsExistInWord(string firstWord, string secondWord, string largeWord) {
    // check iff all letters of first and second word are in larger word

    // create a dictionary of all letters in largeWord
    std::map<char, int> lettersMap;
    for (int i = 0; i < largeWord.size(); i++)
    {
        if (!lettersMap.count(largeWord.at(i))) {
            lettersMap.insert({largeWord.at(i), 1});
        } else {
            lettersMap[largeWord.at(i)]++;
        }
    }
    for (int i = 0; i < firstWord.size(); i++) {
        if (!lettersMap.count(firstWord[i]))
            return false;
        lettersMap[firstWord.at(i)]--;
    }
    for (int i = 0; i < secondWord.size(); i++) {
        if (!lettersMap.count(secondWord[i]))
            return false;
        lettersMap[secondWord.at(i)]--;
    }

    for (int i = 0; i < lettersMap.size(); i++) {
        if (lettersMap[i])
            return false;
    }
    return true;
}
int main() {

    // init rand function
    srand(time(NULL));

    string dictionaryPath = "words.txt"; 
    vector<string> allNineLetterWords = findWords(dictionaryPath, 9);
    vector<string> allFourLetterWords = findWords(dictionaryPath, 4);
    vector<string> allFiveLetterWords = findWords(dictionaryPath, 5);
    for (int k = 0; k < allNineLetterWords.size(); k++) {
        for (int i = 0; i < allFourLetterWords.size(); i++) {
            for (int j = 0; j < allFiveLetterWords.size(); j++) {
                if (twoWordsExistInWord(allFourLetterWords[i], allFiveLetterWords[j], allNineLetterWords[k])) {
                    std::cout << allNineLetterWords[k] << ", " << allFourLetterWords[i] << allFiveLetterWords[j] << std::endl;
                }
            }
        }
    }


    return 0;
}

将产生:

entranced, acnetrend

womankind, amidknown

aerations, asiatoner

exorcises, coresixes

...

哈哈,玩得开心!

关于c++ - 如何从文本文件中获取长度为 9 的单词?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58262822/

相关文章:

c++ - Qt5.6信号与槽重载

c++ - 为什么 Base 类和 Drive 类在启动 Drive 实例时具有相同的虚拟指针但有 2 个 vtable

c++ - 使用STL对部分 vector 进行排序

c++ - 如何将整数初始化为 "a = {1,}"编译?

c++ - move 或命名返回值优化 (NRVO)?

c++ - 用于与 arduino 进行串行通信的 struct termios 设置

c++ - 具有不可 move 的默认可构造值类型的 map/unordered_map

c++返回子类,其中函数返回指向父类(super class)的指针

c++ - 不使用 wstrings 和 cout 编译的简单 C++ 程序

c++ - 如何在没有 <array> 的情况下声明具有统一类型的元组?