encode static method
Encodes this string using Soundex (first letter + 3 digits).
Non-alpha characters are ignored. Returns 4-char string (letter + 3 digits), or empty string if no letters.
Example:
SoundexUtils.encode('Robert'); // 'R163'
SoundexUtils.encode('Rupert'); // 'R163'
Audited: 2026-06-12 11:26 EDT
Implementation
static String encode(String s) {
if (s.isEmpty) return '';
final String letters = s.toUpperCase().replaceAll(RegExp(r'[^A-Z]'), '');
if (letters.isEmpty) return '';
final StringBuffer out = StringBuffer(letters[0]);
int prev = _code(letters[0]);
int count = 1;
for (int i = 1; i < letters.length && count < _soundexCodeLength; i++) {
final String ch = letters[i];
final int c = _code(ch);
if (c != 0) {
// Only emit a new digit when it differs from the previous coded letter
// (adjacent same-code letters collapse), but always remember it.
if (c != prev) {
out.write(c);
count++;
}
prev = c;
} else if (_isVowel(ch)) {
// Vowels (A,E,I,O,U,Y) BREAK adjacency: reset prev so a following
// consonant with the same code as the previous one is still coded
// (e.g. 'Gauss' -> G200, not G000). H and W are transparent and must
// NOT reset prev, so they fall through and leave it unchanged.
prev = 0;
}
}
while (count < _soundexCodeLength) {
out.write(_zero);
count++;
}
return out.toString();
}