C++ std::string 比较(检查字符串是否以另一个字符串开头)

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/931827/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-27 18:02:27  来源:igfitidea点击:

std::string comparison (check whether string begins with another string)

c++stringstlcompare

提问by Hymanhab

I need to check whether an std:string begins with "xyz". How do I do it without searching through the whole string or creating temporary strings with substr().

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

回答by Wacek

I would use compare method:

我会使用比较方法:

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

if (s.compare(0, t.length(), t) == 0)
{
// ok
}

回答by Neutrino

An approach that might be more in keeping with the spirit of the Standard Library would be to define your own begins_with algorithm.

一种可能更符合标准库精神的方法是定义您自己的 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());
}

This provides a simpler interface to client code and is compatible with most Standard Library containers.

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

回答by Alex Ott

Look to the Boost's String Algolibrary, that has a number of useful functions, such as starts_with, istart_with (case insensitive), etc. If you want to use only part of boost libraries in your project, then you can use bcp utility to copy only needed files

看看Boost的String Algo库,它有很多有用的函数,比如starts_with、istart_with(不区分大小写)等。如果你只想在你的项目中使用boost库的一部分,那么你可以使用bcp工具来复制只需要文件

回答by Alejadro Xalabarder

It seems that std::string::starts_with is inside C++20, meanwhile std::string::find can be used

似乎 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
}

回答by 1800 INFORMATION

I feel I'm not fully understanding your question. It looks as though it should be trivial:

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

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

This only looks at (at most) the first three characters. The generalisation for a string which is unknown at compile time would require you to replace the above with a loop:

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

// look for t at the start of s
for (int i=0; i<s.length(); i++)
{
  if (s[i]!=t[i])
    return false;
}