字符串比较(检查字符串是否以另一个字符串开头)

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

68055 次浏览

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;
}

Look to the Boost's String Algo library, 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

I would use compare method:

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


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

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

#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.

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

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


if (s1.find(s2) == 0)
{
// ok, s1 starts with s2
}