c++ - 按单个字符比较两个字符串 C++

标签 c++ string split

正在开发一个将参数与文件中的文本进行比较的程序(我的文件是一本包含大量英文单词的字典)。

目前,应用程序仅适用于完全匹配的字符串。

想知道是否有一种方法可以将输入的部分字符串与文件中的完整字符串进行比较并使其匹配。 例如,如果 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/

相关文章:

java - 为什么这个公共(public)字符串函数不起作用?

java - 如何删除字符串中的多余空格和新行?

Java split() 一个由您要拆分的字符串组成的字符串?

javascript - 将两个单词拆分为变量

c++ - 单链表不起作用 (C++)

c++ - 在进行其他计算时忽略用户输入

c++ - 哈希函数和哈希表中的存储

c++ - 指针的值初始化在 C++ 中究竟做了什么?

c - fgets 不提示用户输入。有什么不同?

php - 在 PHP 中拆分嵌套括号的正确方法,例如 "root[one[a,b,c],two[d,e,f]]"到数组?