Skip to content

Instantly share code, notes, and snippets.

@00-matt
Last active August 13, 2019 16:38
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save 00-matt/7b393ea1bd955f1634c2dde428d93a2e to your computer and use it in GitHub Desktop.
Save 00-matt/7b393ea1bd955f1634c2dde428d93a2e to your computer and use it in GitHub Desktop.
the
the quick
the quick brown
the quick brown fox
quick
quick brown
quick brown fox
quick brown fox jumped
brown
brown fox
brown fox jumped
brown fox jumped over
fox
fox jumped
fox jumped over
fox jumped over the
jumped
jumped over
jumped over the
jumped over the lazy
over
over the
over the lazy
over the lazy dog
the lazy dog
the lazy
the
lazy dog
lazy
dog
#include <iostream>
#include <string>
#include <vector>
std::vector<std::string_view> create_index(std::string_view source, int max) {
std::vector<std::string_view> idx;
const char *this_word_start = source.begin();
const char *next_word_start;
int cur_phrase_len = 1;
for (auto it = source.begin(); it != source.end(); it++) {
if (*it != ' ') {
continue;
}
if (cur_phrase_len == 1) {
next_word_start = it + 1;
}
idx.push_back(
std::string_view(this_word_start, std::distance(this_word_start, it)));
if (cur_phrase_len++ == max) {
it = next_word_start;
this_word_start = next_word_start;
cur_phrase_len = 1;
}
}
return idx;
}
int main() {
auto idx = create_index("the quick brown fox jumped over the lazy dog", 4);
for (auto &str : idx) {
std::cout << str << "\n";
}
}
the
the quick
the quick brown
the quick brown fox
quick
quick brown
quick brown fox
quick brown fox jumped
brown
brown fox
brown fox jumped
brown fox jumped over
fox
fox jumped
fox jumped over
fox jumped over the
jumped
jumped over
jumped over the
jumped over the lazy
over
over the
over the lazy
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment