c++ - 关于c++中的 'compare'函数

标签 c++ string compare

我想比较两个字符串,并计算在字符串 A 中可以找到多少个子字符串 B。

但它总是显示'0'。怎么了?

int getMatchCount(string a, string b)
{
    int num;
    num = 0;
    for (int i = 0; i < a.length() - b.length() + 1; ++i)
    {
        if (a.compare(i, b.length() + i, b, 0, b.length()) == 0) // comapre function
        {
            num = num + 1;
        }
        else
        {
            continue;
        }
    }
}


int main()
{
    int x = getMatchCount("sisisisisisisisis", "si");
    cout << x << endl;
}

最佳答案

  1. b.length() + i错了,要比较的长度是b.length() .
  2. 你不需要 continue .
  3. 您需要返回值。
  4. i < a.length() - b.length();对于 a = "sisisisi", b = "si", 将计数 3,但是 i <= a.length() - b.length();将计数 4。
int getMatchCount(string a, string b)
{
    int num;
    num = 0;
    for (int i = 0; i <= a.length() - b.length(); i++) {
        if (a.compare(i, b.length(), b, 0, b.length()) == 0) {
            num = num + 1;
        }
    }

    return num;
}

int main()
{
    int x = getMatchCount("sisisisisisisisis", "si");
    cout << x << endl;
    return 0;
}

关于c++ - 关于c++中的 'compare'函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48800834/

相关文章:

c++ - spdlog 错误 : "don' t know how to format the type, 包括 fmt/ostream.h(如果它提供了应使用的运算符 <<)”

c++ - 如何在非透明窗口中具有透明小部件?

在C中逐个字符地比较两个字符串

Java - 字符串和数组引用

c++ - 共享内存: MapViewOfFile returns error 5

c++ - std::bind to std::function 转换问题

c# - 如何在我的字符串中插入 '-'?

haskell - 比较列表中的所有元素 haskell

java - 检查一个字符串是否由与另一个字符串相同的字母构成

php - 突出显示 MySQL 数据结果