jackhab
jackhab

Reputation: 17698

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

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

Upvotes: 90

Views: 69013

Answers (5)

Alejadro Xalabarder
Alejadro Xalabarder

Reputation: 1630

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
}

Upvotes: 4

Neutrino
Neutrino

Reputation: 9604

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.

Upvotes: 14

Wacek
Wacek

Reputation: 4346

I would use compare method:

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

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

Upvotes: 163

Alex Ott
Alex Ott

Reputation: 87174

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

Upvotes: 10

1800 INFORMATION
1800 INFORMATION

Reputation: 135295

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

Upvotes: 0

Related Questions