commonCharacters method
Returns a Set
of the common characters between the two String
s.
The String
is case sensitive & sorted by default.
Example
String foo = 'Hello World';
List<String> commonLetters = foo.commonCharacters('World Hello'); // returns ['H', 'e', 'l', 'o', 'r', 'w', 'd'];
String foo = 'Hello World';
List<String> commonLetters = foo.commonCharacters('World Hello!'); // returns ['H', 'e', 'l', 'o', 'r', 'w', 'd'];
Implementation
Set<String> commonCharacters(
String otherString, {
bool caseSensitive = true,
bool sort = true,
bool includeSpaces = false,
}) {
if (this.isBlank) {
return {};
}
String processString(String input) {
return (caseSensitive ? input : input.toLowerCase())
.split('')
.where((char) => includeSpaces || char != ' ')
.join('');
}
final Set<String> commonLettersSet = {};
final Set<String> otherStringSet =
processString(otherString).split('').toSet();
for (final letter in processString(this).split('')) {
if (otherStringSet.contains(letter)) {
commonLettersSet.add(letter);
}
}
if (sort) {
final List<String> sortedList = commonLettersSet.toList()..sort();
return sortedList.toSet();
} else {
return commonLettersSet;
}
}