splitWords method

List<string> splitWords([
  1. WordSplitMode mode = WordSplitMode.wordsOnly
])

Split a string into a list of words and word splitter following the mode

mode can be WordSplitMode.wordsOnly, WordSplitMode.whitespace, WordSplitMode.keepSplitters

  • if mode is WordSplitMode.wordsOnly, the string is splitted by any char of Get.wordSplitters resulting in a list containing only words. this is the default mode
  • if mode is WordSplitMode.whitespace, the string is splitted by any char of Get.whiteSpaceOrBreakChars resulting in a list containing only words and word splitters, excluding white spaces or breaklines.
  • if mode is WordSplitMode.keepSplitters, the final list will contain all characters of original string. Each entry of the list will be a full word or a word splitter, in exactly the same order as the original string.

Implementation

List<string> splitWords([WordSplitMode mode = WordSplitMode.wordsOnly]) {
  if (isBlank) {
    return [];
  } else if (mode == WordSplitMode.wordsOnly) {
    return splitAny(wordSplitters, false);
  } else if (mode == WordSplitMode.whitespace) {
    return splitAny(whiteSpaceOrBreakChars, false);
  } else if (mode == WordSplitMode.keepSplitters) {
    var entries = <string>[];
    var entry = '';
    for (var i = 0; i < length; i++) {
      var char = this[i];
      if (wordSplitters.contains(char)) {
        if (entry.isNotEmpty) {
          entries.add(entry);
          entry = '';
        }
        entries.add(char);
      } else {
        entry += char;
      }
    }
    if (entry.isNotEmpty) entries.add(entry);
    return entries;
  } else {
    return [];
  }
}