Find all a substring's occurrences and locations

前端 未结 2 1049
野的像风
野的像风 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 10:55

    I know an answer has been accepted, but this will also work, and will save you having to load in the file to a string..

    #include 
    #include 
    #include 
    #include 
    
    using namespace std;
    
    int main(void)
    {
      const char foo[] = "foo";
      const size_t s_len = sizeof(foo) - 1; // ignore \0
      char block[s_len] = {0};
    
      ifstream f_in();
    
      vector f_pos;
    
      while(f_in.good())
      {
        fill(block, block + s_len, 0); // pedantic I guess..
        size_t cpos = f_in.tellg();
        // Get block by block..
        f_in.read(block, s_len);
        if (equal(block, block + s_len, foo))
        {
          f_pos.push_back(cpos);
        }
        else
        {
          f_in.seekg(cpos + 1); // rewind
        }
      }
    }
    

提交回复
热议问题