C++ std::string 中是否有任何函数可以计算两个字符串的相同起始字符的总数或任何最佳方法

Is there any function in C++ std::string that count total number of same starting characters of two strings or any best way to do

本文关键字:任何 方法 字符串 字符 两个 最佳 是否 string std 函数 C++      更新时间:2023-10-16

例如。

abcfgf
abdef

ans=2 {"ab" 是一个常见的起始字符}

您可以使用

std::mismatch ,它返回一对迭代器,指示序列开始不同的各个迭代器。

例如,要计算常见前缀的长度,您可以执行以下操作:

#include <iostream>                                                                                                                                                                                         
#include <iterator>
#include <string>
#include <algorithm>
using namespace std;
int main() {
    const string l = "abcde", r = "abcdfgh";
    cout << distance(begin(l), mismatch(begin(l), end(l), begin(r)).first) << endl;
}

似乎有一个内置函数可以做到这一点,如这个答案所示。

但是,您可以通过简单地使用循环(如果需要,但不建议它(来做到这一点,如下所示:

#include <iostream>
#include <string>
using namespace std;
int main()
{
    string str1 = "abcfgf";
    string str2 = "abdet";
    int counter = 0;
    for(int i = 0; i < str1.size() && i < str2.size(); ++i)
        if(str1[i] == str2[i])
            counter++;
    cout << counter << endl;
    return 0;
}

输出:

阿拉伯数字