函数返回两个字符串的第一个公共字符

时间:2019-12-09 20:09:14

标签: c++ string function

在c ++中的字符串库中是否有一个函数接受2个字符串并返回它们之间的第一个公共字符? 例如:

string x = "HelloWorld";
string y = "HelloFriends";

此函数采用字符串x和y,返回字符串包含“ Hello”,这是区别之前的第一个常见字符。 如果字符串库中没有这样的函数,我能知道如何实现这样的函数吗?

1 个答案:

答案 0 :(得分:1)

您可能正在寻找的算法函数是std::mismatch

#include <algorithm>
#include <string>
#include <iostream>

int main()
{
    std::string x = "HelloWorld"; 
    std::string y = "HelloFriends";
    auto pr = std::mismatch(x.begin(), x.end(), y.begin());
    std::string out(x.begin(), pr.first);
    std::cout << out;
}

输出:

Hello

请注意,如果您使用的是C ++ 14之前的编译器,则需要检查第一个范围是否短于第二个范围。

更好地阅读链接的页面,因为此功能增加了更多的重载,具体取决于您使用的C ++版本。