Find all substring’s occurrences and locations

string str,sub; // str is string to search, sub is the substring to search for

vector<size_t> positions; // holds all the positions that sub occurs within str

size_t pos = str.find(sub, 0);
while(pos != string::npos)
{
    positions.push_back(pos);
    pos = str.find(sub,pos+1);
}

Edit
I misread your post, you said substring, and I assumed you meant you were searching a string. This will still work if you read the file into a string.

Leave a Comment

tech