Mittwoch, 7. November 2012

Split line in C++

inline vector split(string line, size_t minWordLength) {
  vector ret;
  size_t pos = 0;
  while (pos < line.size()) {
    while (pos < line.size() && !isalpha(line[pos]))
      pos++;
    size_t wordStart = pos;
    while (pos < line.size() && isalpha(line[pos]))
      pos++;
    size_t wordEnd = pos;
    if (wordEnd >= wordStart + minWordLength) {
      string word = line.substr(wordStart, wordEnd - wordStart);
      ret.push_back(word);
    }
  }
  return ret;
}
This inline helper function splits a line of characters (string) and returns a list (vector) of words the line consists of. Given the minWordLength parameter only words with a minimum length of this size will be considered for the output.
The line is split by delimiters being of non-character type like a space or dashes. Of course, one could also use a delimiter as parameter or a list of those to determine the separators within the line...
To use this function string and vector from the STL are required.

Keine Kommentare:

Kommentar veröffentlichen