3

Eg.

abcfgf
abdef

ans=2 {"ab" is a common starting character}

Clifford
  • 88,407
  • 13
  • 85
  • 165
r_ranjan
  • 189
  • 1
  • 2
  • 5
  • 2
    There's nothing with asking precise questions like this, imho. We should all strive to maximise our use of standard library functions. – Bathsheba May 13 '17 at 13:26
  • Possible duplicate of [Check if one string is a prefix of another](http://stackoverflow.com/questions/7913835/check-if-one-string-is-a-prefix-of-another) – CroCo May 13 '17 at 18:39
  • @πάνταῥεῖ: Except, the C++ Standard Library does provide such a function. You have to be very careful when claiming something doesn't exist. – Ben Voigt May 14 '17 at 05:38

2 Answers2

12

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;
}
Ami Tavory
  • 74,578
  • 11
  • 141
  • 185
1

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

Community
  • 1
  • 1
gsamaras
  • 71,951
  • 46
  • 188
  • 305