Text Corrector Function

Viewed 72

I'm trying to make a stringCorrector function for avoiding non-English words, but don't know how to implement this to string in Dart; as an example;

İstanbul ====> Istanbul, New York===> NewYork, İşÇöÜ===>IsCoU

String stringCorrector(String string) {
    Map<String, String> correcterMap = {
      'ö': 'o',
      'ü': 'u',
      'Ö': 'O',
      'Ü': 'U',
      'İ': 'I',
      'ı': 'i',
      'ğ': 'g',
      'Ğ': 'G',
      ' ': ''
    };
  }
2 Answers

May be I can help you if I understand the use of this. For the first two examples, it is relatively easy, but for the third one you will need to have a whole map of values to replace.

You would get something like this :

String stringCorrector(String string) {
Map<String, String> correcterMap = {
  'ö': 'o',
  'ü': 'u',
  'Ö': 'O',
  'Ü': 'U',
  'İ': 'I',
  'ı': 'i',
  'ğ': 'g',
  'Ğ': 'G',
  ' ': '',
};

correcterMap.forEach((key, value) {
  string = string.replaceAll(RegExp(key), value);
});

return string;}

It's just a matter of mapping the string and reducing that result.

String stringCorrector(String string) {
  Map<String, String> correcterMap = {
    'ö': 'o',
    'ü': 'u',
    'Ö': 'O',
    'Ü': 'U',
    'İ': 'I',
    'ı': 'i',
    'ğ': 'g',
    'Ğ': 'G',
    ' ': ''
  };
  return string.runes.map(
    (int charCode) {
      String char = String.fromCharCode(charCode);
      return correcterMap[char] ?? char;
    }
  ).reduce((a, b) => a + b);
}
Related