简体   繁体   English

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

[英]Function return the first common characters of two strings

is there is a function in the string library in c++ which takes 2 strings and return the first common characters between them? c++ 中的字符串库中是否有一个函数,它接受 2 个字符串并返回它们之间的第一个公共字符? for example:例如:

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

this function takes string x and string y and return string contains "Hello" which is the first common characters before difference.此函数接受字符串 x 和字符串 y 并返回字符串包含“Hello”,这是差异之前的第一个公共字符。 if there's not a function like this in the string library can i know how to implement a function like this?如果字符串库中没有这样的函数,我可以知道如何实现这样的函数吗?

The algorithm function you probably are looking for is std::mismatch :您可能正在寻找的算法函数是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;
}

Output:输出:

Hello

Note that if you're using a compiler pre C++ 14, you need to check for the first range being shorter than the second range.请注意,如果您使用的是 C++ 14 之前的编译器,则需要检查第一个范围是否比第二个范围短。

Better to read the linked page, since this function has added further overloads, depending on the version of C++ you're using.最好阅读链接页面,因为此函数添加了更多重载,具体取决于您使用的 C++ 版本。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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