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

↘锁芯ラ 提交于 2019-12-12 07:08:18

问题


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().


回答1:


I would use compare method:

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

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



回答2:


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.




回答3:


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




回答4:


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
}



回答5:


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


来源:https://stackoverflow.com/questions/931827/stdstring-comparison-check-whether-string-begins-with-another-string

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!