繁体   English   中英

C ++ std :: string中是否有任何函数可以计算两个字符串的相同起始字符的总数或任何最佳方法

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM