mirror of
https://gitee.com/johng/gf.git
synced 2024-12-03 04:37:49 +08:00
59 lines
1.4 KiB
Go
59 lines
1.4 KiB
Go
// Copyright 2018 gf Author(https://github.com/gogf/gf). All Rights Reserved.
|
|
//
|
|
// This Source Code Form is subject to the terms of the MIT License.
|
|
// If a copy of the MIT was not distributed with this file,
|
|
// You can obtain one at https://github.com/gogf/gf.
|
|
|
|
package gstr
|
|
|
|
// Soundex calculates the soundex key of a string.
|
|
// See http://php.net/manual/en/function.soundex.php.
|
|
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
|
|
char := str[i]
|
|
if char < '\u007F' && 'a' <= char && char <= 'z' {
|
|
code = int(char - 'a' + 'A')
|
|
} else {
|
|
code = int(char)
|
|
}
|
|
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; small++ {
|
|
sd[small] = '0'
|
|
}
|
|
return string(sd)
|
|
}
|