首页 > 解决方案 > 如何将某个字符与字符串的另一个字符进行比较

问题描述

在以下代码中,我无法比较两个给定字符串的特定字母。

#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声明出来,它工作正常,但显然没有给我正确的答案。有什么办法可以比较这两个字符串(第二个字符串比第一个字符串大)来确定第一个字符串是否是第二个字符串的开头?

谢谢!

标签: c++

解决方案


  • 您正在递增i而不是j在第 32 行的循环中
  • 你在第 33 行有你的测试 -stillIs = false如果字符匹配,你想设置,(即,!=

我还没有完全阅读你的代码,但是这两个问题突然出现在我身上,所以看看是否能解决它


推荐阅读