在搜索单词时使用问号来代表任何字符
Using a question mark when searching for a word to stand for any character
对于我正在尝试编写的程序,读取一个.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 中的查找函数。希望这有帮助。祝你好运!
相关文章:
- 在处理任何字符大小的模板中使用字符串文本
- 使用 ISdigit 通知任何检测到的非法字符
- 是否有任何区域设置会影响宽字符编码?
- C++ - 将任何文件的字节读取到无符号字符数组中
- 在 std::getline() 上使用任何字符作为分隔符
- 用wchar_t处理 unicode 字符好吗?它不会引起任何问题吗?
- 将十六进制字符数组存储在字节数组中,而无需更改为 ASCII 或其他任何东西
- 使用 C 字符串和指针.删除除小写和空格以外的任何字符
- 我的 c++ 程序不打印任何字符,但是如果我将它们更改为 int,代码可以完美运行
- 如果在输入中,我给出任何字符数据,为什么这不会抛出部分
- 如何在不删除任何字符的情况下将字符从字符串中的某个位置移动到其最前面
- Strchr不起作用,或者我需要一个替代方案来检查给定字符串中的任何字符是否是另一个字符串的一部分
- 不分配任何字符内存的常量字符串构造函数?
- 如何将数字拆分为其数字并将它们相加,如果存在任何字符,则应"invalid input"输出?
- 如果我得到任何字符,请退出程序
- 在搜索单词时使用问号来代表任何字符
- 为什么程序在 while 循环中继续输入任何字符
- iStream 对象不读取任何字符
- 匹配除双引号以外的任何字符
- 在字符串数组中添加任何字符