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?
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.
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With