Is there any function in C ++ std :: string that counts the total number of identical starting characters from two strings, or any better way to do
2 answers
You can use std::mismatch
that returns a pair of iterators indicating the appropriate iterators where the sequences start to differ.
To calculate the length of common prefixes, you can 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;
}
+10
source to share
There seems to be a built-in function for this, as shown in this.
However, you can do this simply by using a loop (if you like, but don't suggest it), for example:
#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
+1
source to share