Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Searching std::string between a limit

Tags:

c++

string

stl

if you know the start and end positions in string from where to begin and end the search. For example -

string s = StringStringString

|S |t |r |i |n |g |S |t |r |i |n |g |S |t |r |i |n |g
 0  1  2  3  4  5  6  7  8  9  10 11 12 13 14 15 16 17

How would you find "tr" in the string specifying the the position to begin search is at index 6 and the position to end the search is index 9.

I'm trying a set a limit of search so it wouldn't go beyond it.

like image 473
cpx Avatar asked Mar 06 '10 21:03

cpx


2 Answers

If you really want to limit the length of the sequence that gets traversed (presumably because the string is very long compared to the interesting region), use std::search and pass it the corresponding iterators into the string.

like image 145
avakar Avatar answered Sep 19 '22 06:09

avakar


Given start as the position where you want to start searching, and stop as the position where you want to stop searching:

int pos = your_string.find("tr", start);

if (pos == std::string::npos || pos > stop)
    // it wasn't found.

This assumes that what you're giving as stop is that last position at which a match can begin. So (for example) if you want to match a substring that's four characters long, it can extend up to three characters past the stop position. If you want to assure the end of the substring is before the stop point, you'd subtract the length of the substring from stop when you compare to pos

like image 22
Jerry Coffin Avatar answered Sep 22 '22 06:09

Jerry Coffin