Go 实现 soundex 算法

【转】http://www.syyong.com/Go/Go-implements-the-soundex-algorithm.html

 

SOUNDEX 返回由四个字符组成的代码 (SOUNDEX) 以评估两个字符串的相似性。

Soundex("Euler")       == Soundex("Ellery");    // E460
Soundex("Gauss")       == Soundex("Ghosh");     // G200
Soundex("Hilbert")     == Soundex("Heilbronn"); // H416
soundex("Knuth")       == Soundex("Kant");      // K530
Soundex("Lloyd")       == Soundex("Ladd");      // L300
Soundex("Lukasiewicz") == Soundex("Lissajous"); // L222

Soundex

// soundex()
// Calculate the soundex key of a string.
func Soundex(str string) string {
    if str == "" {
        panic("str: cannot be an empty string")
    }
    table := [26]rune{
        0, '1', '2', '3',           // A, B, C, D
        0, '1', '2',                // E, F, G
        0,                          // H
        0, '2', '2', '4', '5', '5', // I, J, K, L, M, N
        0, '1', '2', '6', '2', '3', // O, P, Q, R, S, T
        0, '1',                     // U, V
        0, '2',                     // W, X
        0, '2',                     // Y, Z
    }
    last, code, small := -1, 0, 0
    sd := make([]rune, 4)
    // build soundex string
    for i := 0; i < len(str) && small < 4; i++ {
        // ToUpper
        if str[i] < '\u007F' && 'a' <= str[i] && str[i] <= 'z' {
            code = int(str[i] - 'a' + 'A')
        } else {
            code = int(str[i])
        }
        if code >= 'A' && code <= 'Z' {
            if small == 0 {
                sd[small] = rune(code)
                small++
                last = int(table[code-'A'])
            } else {
                code = int(table[code-'A'])
                if code != last {
                    if code != 0 {
                        sd[small] = rune(code)
                        small++
                    }
                    last = code
                }
            }
        }
    }
    // pad with "0"
    for small < 4 {
        sd[small] = '0'
        small++
    }
    return string(sd)
}

 

Github地址

https://github.com/syyongx/php2go

posted @ 2018-04-25 11:05  syyong  阅读(218)  评论(0编辑  收藏  举报