findClosestMatchingWordInDictionary function

String findClosestMatchingWordInDictionary(
  1. String word
)

Finds the closest matching word in the dictionary for a given word.

This function takes a word string to find a match for and uses the Levenshtein distance to find the closest word in the dictionary. It also handles special cases for plural words ending with 's' or 'S'.

Returns the closest matching word with the original casing preserved for unchanged letters.

Implementation

String findClosestMatchingWordInDictionary(String word) {
  String suggestion = findClosestWord(englishWords, word.toLowerCase());
  String lastChar = word[word.length - 1];
  if (lastChar == 's' ||
      lastChar == 'S' && (word.length - 1 == suggestion.length)) {
    suggestion += lastChar;
  }
  // Preserve original casing for unchanged letters
  if (word.length == suggestion.length) {
    String result = '';
    for (int i = 0; i < word.length; i++) {
      if (word[i].toLowerCase() == suggestion[i].toLowerCase()) {
        result += word[i]; // Keep original casing
      } else {
        result += suggestion[i]; // Use suggestion's character
      }
    }
    word = result;
  } else {
    word = suggestion;
  }
  return word;
}