JT1
JT1

Reputation: 453

C++ substring check

I'm given two strings s1, s2 and an integer i. I want to check if the substring of s1 starting at index i of the same length as s2 equals s2. I know this is trivial to implement with a little loop, but I would prefer to use a library method if it exists.

Upvotes: 0

Views: 133

Answers (3)

thang
thang

Reputation: 3466

As discussed in the comments, here's an in place solution using string::compare (http://www.cplusplus.com/reference/string/string/compare/)

    s1.compare(i,s2.length(),s2)==0

Which would throw an std::out_of_range exception if (i>=s1.length()). Otherwise, it works. To avoid the out_of_range exception, just add something to short circuit the compare:

    (i<s1.length()) && (s1.compare(i,s2.length(),s2)==0)

Upvotes: 1

stefan
stefan

Reputation: 10345

I would do it using std::equal with a check of proper size first. That way it directly works for vectors as well. The check of sizes is necessary to avoid invalid iterators:

if ( i + s2.size() > s1.size() )
{
    return false;
}
auto s1beg = s1.cbegin() + i;
auto s1end = s1.cbegin() + i + s2.size();
return std::equal(s1beg, s1end, s2.cbegin());

If you want to support any ranges, use std::advance to create the start and end iterator:

auto s1beg = s1.cbegin();
std::advance(s1beg, i);
auto s2end = s1beg;
std::advance(s2beg, s2.size());

Here's a demo for both strings and a list. A further design decision may allow different container types as well.

Upvotes: 1

Sam Varshavchik
Sam Varshavchik

Reputation: 118350

bool is_sub_string=i <= s1.size() && s1.substr(i, s2.size()) == s2;

Upvotes: 0

Related Questions