Code

Code

Soundex Class for Java


// reference: http://en.wikipedia.org/wiki/Soundex
public class SoundexUtil {

	// public static void main(String[] args) {
	// 	System.out.println(soundex("Gauss")); // G200
	// 	System.out.println(soundex("AHN")); // A500
	// }

	public static String soundex(String text) {
		StringBuilder builder = new StringBuilder();
		int numberCounter = 0;

		for (int i = 0; i < text.length(); ++i) {
			char c = text.charAt(i);
			if (i == 0) {
				builder.append(c);

			} else {

				char number = 0;

				switch (Character.toLowerCase(c)) {
				case 'a':
				case 'e':
				case 'h':
				case 'i':
				case 'o':
				case 'u':
				case 'w':
				case 'y':
					continue;

				case 'b':
				case 'f':
				case 'p':
				case 'v':
					number = '1';
					break;

				case 'c':
				case 'g':
				case 'j':
				case 'k':
				case 'q':
				case 's':
				case 'x':
				case 'z':
					number = '2';
					break;

				case 'd':
				case 't':
					number = '3';
					break;

				case 'l':
					number = '4';
					break;

				case 'm':
				case 'n':
					number = '5';
					break;

				case 'r':
					number = '6';
					break;
				}

				if (number > 0
						&& builder.charAt(builder.length() - 1) != number) {
					builder.append(number);
					++numberCounter;
				}
			}
		}

		while (numberCounter < 3) {
			builder.append('0');
			++numberCounter;
		}

		String soundexText = builder.toString();
		return soundexText.substring(0, 4);
	}
}