簡體   English   中英

如何將某個字符與字符串的另一個字符進行比較

[英]How to compare a certain character with another character of a string

在以下代碼中,我無法比較兩個給定字符串的特定字母。

#include <bits/stdc++.h>

using namespace std;

int main() {

    int m, n;
    cin >> m >> n;
    cin.ignore();

    string phrases[m];
    string records[n];

    for (int i = 0; i < m; i++) {
        getline(cin, phrases[i]);
    }

    for (int i = 0; i < n; i++) {
        getline(cin, records[i]);
    }

    int lowBound;
    sort(phrases, phrases + m);
    int ans = 0;
    bool stillIs;
    for (int i = 0; i < n; i++) {
        lowBound = lower_bound(phrases, phrases + m, records[i]) - phrases;
        if (lowBound == m) {
            continue;
        }
        stillIs = true;
        for (int j = 0; j < records[i].length(); i++) {
            if (records[i][j] == phrases[lowBound][j]) {
                stillIs = false;
            }
        }
        if (stillIs) {
            ans++;
        }
    }

    cout << ans;

    return 0;
}

在第 33 行,如果 (records[i][j] == phrases[lowBound][j]),它不會給我一個錯誤,但是如果我用這一行運行它,什么都不會發生,但是當我評論 if聲明出來,它工作正常,但顯然沒有給我正確的答案。 有什么辦法可以比較這兩個字符串(第二個字符串比第一個字符串大)來確定第一個字符串是否是第二個字符串的開頭?

謝謝!

  • 您在第 32 行的循環中遞增i而不是j
  • 您在第 33 行進行了測試 - 如果字符匹配,您想設置stillIs = false (即!=

我還沒有完全閱讀你的代碼,但是這兩個問題突然出現在我身上,所以看看是否能解決它

暫無
暫無

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

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