The task is to find a substring (needle) in another string (haystack), given the beginning position and end position of the "haystack". The the beginning and end positions follow STL convention, i.e. the end position is the position of the character following the interested range.
For example: find "567" with beg_pos=0
and end_pos=8
in "0123456789" should return 5
, while find "567" with beg_pos=0
and end_pos=4
in "0123456789" should return -1
.
I could imagine two simple implementations:
- Method 1: Use
size_t pos = haystack.find(needle, beg_pos);
to get the substring position, then compare the return valuepos
withend_pos
if found. In the worst case, thefind
function will go until the end of the stringhaystack
, but the search afterend_pos
is unnecessary. The performance might be bad ifhaystack
is long. - Method 2: Use
size_t pos = haystack.substr(beg_pos, end_pos-beg_pos).find(needle);
to find the position, then returnpos+beg_pos
if found. This method avoids the problem of unnecessary searching afterend_pos
, but it requires to allocate a new temporary string, which might also have performance issue.
I am wondering if there is a faster way to accomplish the task.