countWords method Null safety

int? countWords()

Returns the word count in the given string.

The pattern is based on spaces.

Example

String foo = 'Hello dear friend how you doing ?';
int count = foo.countWords() // returns 6 words.

Implementation

int? countWords() {
  if (this == null) {
    return null;
  }
  if (this!.isEmpty) {
    return 0;
  }
  var words = this!.trim().split(RegExp(r'(\s+)'));
  // We filter out symbols and numbers from the word count
  var filteredWords = words.where((e) => e.onlyLatin()!.isNotEmpty);
  return filteredWords.length;
}