Get all N consecutive characters in string using stringstream in C++

  c++, string

I would like something that can window a std::string object into partitions of length N – for example (using a function update):

void main() {
  std::string s = "abcdefg";
  update<2>(s);
  return 0;
}

Calling the above should result in:

ab
bc
cd
ef
fg

I have the following version of the update function:

template<std::size_t size>
void update(std::string s) {
    std::string result(size, '{$content}');
    std::stringstream ss{s};
    int iterations = s.length() - size;
    for (int i = 0; i<iterations; i++) {
        ss.read(&result[0], result.size());
        std::cout << result << std::endl;
    }
    return;
}

but this skips out combinations where the initial character lies at an odd index (the number of combinations is correct in my case, even though there is a repeat)

ab
cd
ef
gf
gf

A side note is that if there are any trailing characters then these should be omitted from the printed values (although I think this would be covered by the parameters of the for loop)

A final note is that I would like this to be as optimised as possible since I would typically be using strings of a very large length (>5M characters long) – my current solution may not be best for this so I am open to suggestions of alternative strategies.

Source: Windows Questions C++

LEAVE A COMMENT