countWords property

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? get countWords {
  if (this == null) return null;
  if (this!.isEmpty) return 0;
  final words = this!.trim().split(RegExp(r'(\s+)'));
  final filteredWords = words.where((e) => e.isNotEmpty);
  return filteredWords.length;
}