similarityTo method
Returns value between 1 and 0. The greater the value, the greater similarity between the strings
Implementation
double similarityTo(String? compare) {
// if both are null
if (isBlank && compare.isBlank) {
return 1;
}
// as both are not null if one of them is null then return 0
if (isBlank || compare.isBlank) {
return 0;
}
final original = this!.replaceAll(RegExp(r'\s+\b|\b\s'), ''); // remove all whitespace
compare = compare!.replaceAll(RegExp(r'\s+\b|\b\s'), ''); // remove all whitespace
// identical
if (original == compare) {
return 1;
}
// both are 1-letter strings
if (original.length == 1 && compare.length == 1) {
return 0;
}
// if either is a 1-letter string
if (original.length < 2 || compare.length < 2) {
return 0;
}
final firstBigrams = <String, int>{};
for (var i = 0; i < original.length - 1; i++) {
final bigram = original.substring(i, i + 2);
final count = firstBigrams.containsKey(bigram) ? firstBigrams[bigram]! + 1 : 1;
firstBigrams[bigram] = count;
}
var intersectionSize = 0;
for (var i = 0; i < compare.length - 1; i++) {
final bigram = compare.substring(i, i + 2);
final count = firstBigrams.containsKey(bigram) ? firstBigrams[bigram]! : 0;
if (count > 0) {
firstBigrams[bigram] = count - 1;
intersectionSize++;
}
}
return (2.0 * intersectionSize) / (original.length + compare.length - 2);
}