正在开发一个将参数与文件中的文本进行比较的程序(我的文件是一本包含大量英文单词的字典)。
目前,应用程序仅适用于完全匹配的字符串。
想知道是否有一种方法可以将输入的部分字符串与文件中的完整字符串进行比较并使其匹配。 例如,如果 arg 是 ap,它会将其匹配到 apple、application alliance ext。
# include <iostream>
# include <fstream>
# include <cstdlib>
# include <string>
using namespace std;
int main ( int argc, char *argv[] ) {
ifstream inFile;
inFile.open("/Users/mikelucci/Desktop/american-english-insane");
//Check for error
if (inFile.fail()) {
cerr << "Fail to Open File" << endl;
exit(1);
}
string word;
int count = 0;
//Use loop to read through file until the end
while (!inFile.eof()) {
inFile >> word;
if (word == argv[1]) {
count++;
}
}
cout << count << " words matched." << endl;
inFile.close();
return 0;
}
最佳答案
如果“匹配”是指“文件中的字符串包含输入中的字符串”,那么您可以使用 string::find 方法。在这种情况下,您的情况应该是这样的:
word.find(argv[1]) != string::npos
如果“匹配”是指“文件中的字符串以输入中的字符串开头”,那么您可以再次使用 string::find,但条件如下:
word.find(argv[1]) == 0
相关文档为here .
关于c++ - 按单个字符比较两个字符串 C++,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41081319/