90

我需要检查 std:string 是否以“xyz”开头。如何在不搜索整个字符串或使用 substr() 创建临时字符串的情况下做到这一点。

4

5 回答 5

164

我会使用比较方法:

std::string s("xyzblahblah");
std::string t("xyz")

if (s.compare(0, t.length(), t) == 0)
{
// ok
}
于 2009-05-31T11:23:32.737 回答
14

一种可能更符合标准库精神的方法是定义您自己的 begin_with 算法。

#include <algorithm>
using namespace std;


template<class TContainer>
bool begins_with(const TContainer& input, const TContainer& match)
{
    return input.size() >= match.size()
        && equal(match.begin(), match.end(), input.begin());
}

这为客户端代码提供了一个更简单的接口,并且与大多数标准库容器兼容。

于 2013-05-15T15:55:49.580 回答
10

查看 Boost 的String Algo库,它有许多有用的函数,例如 starts_with、istart_with(不区分大小写)等。如果您只想在项目中使用部分 boost 库,则可以使用 bcp 实用程序复制只需要文件

于 2009-05-31T10:54:49.130 回答
4

似乎 std::string::starts_with 在 C++20 内部,同时可以使用 std::string::find

std::string s1("xyzblahblah");
std::string s2("xyz")

if (s1.find(s2) == 0)
{
   // ok, s1 starts with s2
}
于 2018-07-04T14:12:37.123 回答
0

我觉得我没有完全理解你的问题。看起来它应该是微不足道的:

s[0]=='x' && s[1]=='y' && s[2]=='z'

这只查看(最多)前三个字符。在编译时未知的字符串的泛化将要求您用循环替换上面的内容:

// look for t at the start of s
for (int i=0; i<s.length(); i++)
{
  if (s[i]!=t[i])
    return false;
}
于 2009-05-31T10:51:31.587 回答