检查一个字符串是否是另一个字符串的前缀 [英] Check if one string is a prefix of another

查看:379
本文介绍了检查一个字符串是否是另一个字符串的前缀的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个字符串,我想比较: String String:。是否有一个库函数在传递这两个字符串时返回true(但是 String OtherString )为false?

I have two strings which I'd like to compare: String and String:. Is there a library function that would return true when passed these two strings (but false for say String and OtherString)?

确切地说,我想知道一个字符串是否是另一个字符串的前缀。

To be precise, I want to know whether one string is a prefix of another.

推荐答案

使用 std :: mismatch 。传入较短的字符串作为第一个迭代器范围,并且较长作为第二个迭代器范围。返回是一对迭代器,第一个是第一个范围中的迭代器,第二个是第二个。如果第一个是第一个范围的结束,那么你知道短字符串是较长字符串的前缀例如

Use std::mismatch. Pass in the shorter string as the first iterator range and the longer as the second iterator range. The return is a pair of iterators, the first is the iterator in the first range and the second, in the second rage. If the first is end of the first range, then you know the the short string is the prefix of the longer string e.g.

std::string foo("foo");
std::string foobar("foobar");

auto res = std::mismatch(foo.begin(), foo.end(), foobar.begin());

if (res.first == foo.end())
{
  // foo is a prefix of foobar.
}

这篇关于检查一个字符串是否是另一个字符串的前缀的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆