countWord method

int countWord(
  1. String targetWord
)

The countWord extension counts the occurrences of a specific word within a given text. It splits the text into words using spaces as delimiters and then counts the occurrences of the target word.

Implementation

int countWord(String targetWord) {
  if (targetWord.split(" ").length > 1) {
    throw ErrorDescription(
        "The method failed because you pass more than single word in targetWord property");
  }
  int count = 0;
  int startIndex = 0;
  final targetLength = targetWord.length;

  while (true) {
    final index = indexOf(targetWord, startIndex);
    if (index == -1) {
      break;
    }
    count++;
    startIndex = index + targetLength;
  }

  return count;
}