【问题标题】:Function return the first common characters of two strings函数返回两个字符串的第一个公共字符
【发布时间】:2019-12-09 20:09:14
【问题描述】:

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

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

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

【问题讨论】:

标签: c++ string function


【解决方案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++ 版本。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2023-03-29
    • 2021-12-17
    • 2012-03-30
    • 1970-01-01
    • 1970-01-01
    • 2020-06-02
    • 1970-01-01
    相关资源
    最近更新 更多