例如。
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;
}
输出:
阿拉伯数字