簡體   English   中英

用單個字符比較兩個字符串C ++

[英]compare two strings by individual characters C++

正在研究一個將參數與文件中的文本進行比較的程序(我的文件是一個包含很多英語單詞的字典)。

現在,該應用程序僅能完全匹配字符串。

想知道是否有一種方法可以將輸入的部分字符串與文件中的完整字符串進行比較,並使其匹配。 例如,如果arg是ap,它將與蘋果應用程序聯盟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

相關文檔在這里

首先將argv[1]復制到字符串中(並非絕對必要,但這會使隨后的比較更加簡單):

std::string target(arg[1]);

然后使用std::equal

if (std::equal(word.begin(), word.end(), target.begin(). target.end()))

如果兩個序列中的較短者與較長者開始處的對應字符匹配,則此形式的equal (在C ++ 14中添加)返回true

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM