Find all a substring's occurrences and locations

前端 未结 2 1053
野的像风
野的像风 2020-11-28 10:22

I\'m writing a program to parse some data saved as text files. What I am trying to do is find the location of every needle in a haystack. I already can read the file in and

2条回答
  •  生来不讨喜
    2020-11-28 11:00

    string str,sub; // str is string to search, sub is the substring to search for
    
    vector 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.

提交回复
热议问题