c++
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
Eg. abcfgf abdef ans=2 {"ab" is a common starting character}
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; }
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
Related Links
OpenGL Renderdoc SSBO / Image
How to transform a range, pair-by-pair with range-v3?
C++ nested class methods
using strcat to concatenate an array of chars [closed]
2D Vector pointer as member of class
Template arguments in constructor of non-template class
Stream operator and abstract class
C++ no cout info displayed
Non duplicate array value in c++
convert int* to int[] in c++
Jsoncpp FastWriter right trim
C++ Ternary operator with scope resolution and condition
Even after many try i am not able to get the complete idea of my c++ code base in office [closed]
Why is the array changed after this function call? [duplicate]
Unexpectedly uninitialised data in call to member function through lambda
Is implementation of double checked singleton thread-safe?