簡體   English   中英

C ++如何將用戶輸入與嚴格排序的字符串列表進行比較?

[英]C++ How can I compare a user input to a list of string with strict ordering?

我正在嘗試創建一個搜索數組函數,其中有一個字符串列表,並接受用戶輸入。 然后,我將用戶輸入與數組中的字符串進行比較,並按照輸入的確切順序輸出與任何字符串匹配的任何字符串。 我不確定從哪里開始。 像這樣:

數組:“ this”,“ is”,“ a”,“ test”

用戶輸入:“ t”

輸出應為“ this”和“ test”

這是我到目前為止所擁有的:

string arr[6] = {"hello", "this", "is", "a", "test", "string"};
vector<string> words;
for (int i=0; i<5; i++) {
    if (a.find(arr[i]) != string::npos) {
        words.push_back(arr[i]);
    }
}

for (int i=0; i<words.size(); i++) {
    cout << words[i] << endl;
}

目前,它僅搜索完全匹配。 我如何才能適應上述情況?

改變這個

if (a.find(arr[i]) != string::npos) 

if (arr[i].find(a) != string::npos) 

您將在字符串列表中一一搜索用戶字符串。

您在此處發布的代碼中存在邏輯錯誤: if (a.find(arr[i]) != string::npos) { ,它在輸入字符串中搜索數組中的單詞,但您想查找根據我的理解,輸入字符串就是數組中的單詞。

除此之外,我寧願使用std::arrayfor each循環使用:

暫無
暫無

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

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