using System.Text.RegularExpressions;
public static class Soundex
public static string For(string word)
const int MaxSoundexCodeLength = 4;
var soundexCode = new StringBuilder();
var previousWasHOrW = false;
word = Regex.Replace(word == null ? string.Empty : word.ToUpper(), @"[^\w\s]", string.Empty);
if (string.IsNullOrEmpty(word))
return string.Empty.PadRight(MaxSoundexCodeLength, '0');
soundexCode.Append(word.First());
for (var i = 1; i < word.Length; i++)
var numberCharForCurrentLetter = GetCharNumberForLetter(word[i]);
if (i == 1 && numberCharForCurrentLetter == GetCharNumberForLetter(soundexCode[0]))
if (soundexCode.Length > 2 && previousWasHOrW && numberCharForCurrentLetter == soundexCode[soundexCode.Length - 2])
if (soundexCode.Length > 0 && numberCharForCurrentLetter == soundexCode[soundexCode.Length - 1])
soundexCode.Append(numberCharForCurrentLetter);
previousWasHOrW = "HW".Contains(word[i]);
return soundexCode.Replace("0", string.Empty).ToString().PadRight(MaxSoundexCodeLength, '0').Substring(0, MaxSoundexCodeLength);
private static char GetCharNumberForLetter(char letter)
if ("BFPV".Contains(letter))
if ("CGJKQSXZ".Contains(letter))
if ("DT".Contains(letter))
if ("MN".Contains(letter))
public static void Main()
Console.WriteLine(Soundex.For("Cadeau"));
Console.WriteLine(Soundex.For("kdo"));
Console.WriteLine(Soundex.For("Michel"));
Console.WriteLine(Soundex.For("Michèle"));