Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find substring between two indices in C++

Tags:

c++

string

I want to find the substring between two indices. The substr(start_index, number_of_characters) function in C++ returns substring based on number of characters. Hence a small hack to use it with start and end indices is as follows:

 // extract 'go' from 'iamgoodhere'
 string s = "iamgoodhere";
 int start = 3, end = 4;
 cout<<s.substr(start,end-start+1); // go

What other methods exist in C++ to get the substring between two indices?

like image 312
FlyingAura Avatar asked May 27 '18 00:05

FlyingAura


2 Answers

You can do this:

std::string(&s[start], &s[end+1])

or this:

std::string(s.c_str() + start, s.c_str() + end + 1)

or this:

std::string(s.begin() + start, s.begin() + end + 1)

These approaches require that end is less than s.size(), whereas substr() does not require that.

Don't complain about the +1--ranges in C++ are always specified as inclusive begin and exclusive end.

like image 141
John Zwinck Avatar answered Sep 21 '22 12:09

John Zwinck


In addition to John Zwinck's answer you can use substr in combination with std::distance:

auto size = std::distance(itStart, itEnd);
std::string newStr = myStr.subStr(itStart, size);
like image 37
patyx Avatar answered Sep 20 '22 12:09

patyx