Reputation: 199
Eg.
abcfgf
abdef
ans=2 {"ab" is a common starting character}
Upvotes: 3
Views: 630
Reputation: 73424
It seems that there is a buildin function to do this, as shown in this answer.
However, you could do it by simply using a loop (if you want, but would not suggest it), like this:
#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;
}
Output:
2
Upvotes: 1
Reputation: 76366
You could use std::mismatch
, which returns a pair of iterators indicating the respective iterators where sequences start to differ.
To count the length of common prefixes, for example, you could do the following:
#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;
}
Upvotes: 12