在搜索单词时使用问号来代表任何字符

Using a question mark when searching for a word to stand for any character

本文关键字:任何 字符 搜索 单词时      更新时间:2023-10-16

对于我正在尝试编写的程序,读取一个.txt文件,然后计算字数(我使用了map(。程序提示用户输入要查找的单词,然后显示该单词在文件中出现的次数。我应该有一个包含"?"的部分来代替单词中的字母,并打印文件中单词符合描述的次数。"?"可以代表另一个字母或空格。我不知道如何使用它,任何帮助将不胜感激!

例:请输入一个词:a??单词 和 在文档中出现 4 次。在文档中出现 1 次的单词。单词 a 在文档中出现 1 次

问号字符由用户输入,可以代表任何其他字符。该程序应该搜索文件并查找并计算适合的任何可能性。例如,如果用户输入了 a?d,则单词"and"可能是计数内容的可能性。

#include <iostream>
#include <map>
#include <fstream>
#include <string>
using namespace std;
int main(int argc, char *argv[]) {
    if (argc != 2)
        cout << "invalid usage" ;
    //open file
    ifstream infile;
    infile.open(argv[1]);
    //variables
    map<string, unsigned int> wCount;
    int count = 0;
    int uCount = 0;
    //lowercase
    while (!infile.eof()) {
        string text;
        infile >> text;
        for (int i=0; i < text.length(); i++) {
            text[i] = tolower(text[i]);
        }
        //count words
        if (wCount.find(text) == wCount.end()) {
            wCount[text] = 1;
            count++;
            uCount++;
        }
        else {
            wCount[text]++;
            count++;
        }
    }
    cout << "The total number of word found in the file was " << count << endl;
    cout << "The number of unique words found was " << uCount << "." << endl;
    cout << "Enter the word you want to find: " << "";
    //find(infile, word);
    string in = "";
    getline(cin, in);
    while(in != "EOF") {
            cout << "The word " << in << " appears " << wCount[in] << " times in the file" << endl;
            cout << "Please enter a word: " << "";
            getline(cin, in);
    }
    return 0;
}

我喜欢这样的问题。他们在计算机科学的大量不同领域都有应用;尤其是生物信息学。这应该让你开始。按照Galik的建议,您可以:

1(从字符串中删除问号字符

std::string strip_wild_card(const std::string &pattern) {
    int q_index = pattern.find("?");
    return pattern.substr(0, q_index);
}

2(查找文本中出现的图案

bool wild_card_compare(const std::string &pattern, const std::string &text) {
    //implement this
    if(pattern is found in text)
        return true
    else
        return false
}

提示:要检查这一点,我们可以使用 STL 中的查找函数。希望这有帮助。祝你好运!