我需要检查一个std:string是否以“xyz”开头。如何在不搜索整个字符串或创建临时字符串的情况下完成它。
我该怎么做呢?我会使用比较方法:
std::string s("xyzblahblah");
std::string t("xyz")
if (s.compare(0, t.length(), t) == 0)
{
// ok
}
一个更符合标准库精神的方法是定义你自己的begins_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());
}
这提供了一个更简单的接口给客户端代码,并且与大多数标准库容器兼容。
查看Boost的String Algo库,其中包含许多有用的功能,例如starts_with、istart_with(不区分大小写)等。如果你想在项目中只使用部分Boost库,那么可以使用bcp实用程序仅复制所需文件。
似乎C++20中包含了std::string::starts_with函数,但是也可以使用std::string::find函数。
std::string s1("xyzblahblah");
std::string s2("xyz")
if (s1.find(s2) == 0)
{
// ok, s1 starts with s2
}
std::string::compare
的被接受答案要好得多,因为它使得检查字符串是否以字面量开头变得容易,而不需要重复字面量本身来找到其大小。感谢您指出C++20的直接解决方案。 - Ruslan我感觉我没有完全理解你的问题。看起来这应该是微不足道的:
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;
}
t
中的终止NUL时,循环终止。 - Jim Balter