Compares two identical values but returns false

55 Views Asked by At

I need to compare each word in the recognized String with the base string. In logcat, I see the two strings are the same but when compared, it returns false. Which step did I go wrong?

This is my code

String check ='HĐ:';
   for(String word in textInLine.split(" ")){

      log("CHECK_WORD_TEXT ${word} AND ${check}");
      log("CHECK_WORD_COMPARE ${word == check}");

      }

And this is Logcat result

[log] CHECK_WORD_TEXT HÐ: AND HĐ:
[log] CHECK_WORD_COMPARE false

I tried with a.contains(b) and a.compare(b)==0 but both returned false results

1

There are 1 best solutions below

5
ali tarek On

you can try checking the string word length to see what's going in here i think one of those words you are comparing together has an extra whitespace maybe you can try using trim() function on string to remove extra white spaces on right and left of the string

also if the comparison is not case senestive you can use toLowerCase() function to ensure that both are same letters

word.toLowerCase().trim() == check.toLowerCase().trim()

i hope that helps you

also there is a builtin function in flutter called identical() that takes two parameters as strings and see if they are identical in everything

This is an optimization, as two strings with the same characters in the same order can be the same object. that's the functionality of identical() function

Edit: after seeing your updated question i see that check string is the one which has an extra whitespace at the end maybe the word doesn't have that extra white space at end so they are not equal

Another solution

import 'package:intl/intl.dart';

void main() {
  String string1 = "HÐ";
  String string2 = "HĐ";

  // Normalize the strings using NFC (Normalization Form Canonical Composition)
  String normalizedString1 = normalize(string1);
  String normalizedString2 = normalize(string2);

  if (normalizedString1 == normalizedString2) {
    print("Strings are equal");
  } else {
    print("Strings are not equal");
  }
}

String normalize(String input) {
  return Normalizer.normalize(input, NormalizerForm.NFC);
}