Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 845
jackhab Avatar asked May 31 '09 10:05

jackhab


People also ask

How do I compare STD strings?

In order to compare two strings, we can use String's strcmp() function. The strcmp() function is a C library function used to compare two strings in a lexicographical manner. Syntax: int strcmp ( const char * str1, const char * str2 );


2 Answers

I would use compare method:

std::string s("xyzblahblah"); std::string t("xyz")  if (s.compare(0, t.length(), t) == 0) { // ok } 
like image 100
Wacek Avatar answered Sep 21 '22 18:09

Wacek


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.

like image 34
Neutrino Avatar answered Sep 22 '22 18:09

Neutrino