![](/img/trans.png)
[英]Is there any way to compare two consecutive elements of a std::set in 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
例如。
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;
}
似乎有一個buildin函數來執行此操作,如此答案所示。
但是,您可以通過簡單地使用循環(如果您願意,但不會建議它)來實現,如下所示:
#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;
}
輸出:
2
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.