github.com/zhongdalu/gf@v1.0.0/g/text/gstr/gstr_soundex.go (about) 1 // Copyright 2018 gf Author(https://github.com/zhongdalu/gf). All Rights Reserved. 2 // 3 // This Source Code Form is subject to the terms of the MIT License. 4 // If a copy of the MIT was not distributed with this file, 5 // You can obtain one at https://github.com/zhongdalu/gf. 6 7 package gstr 8 9 // Soundex calculates the soundex key of a string. 10 // See http://php.net/manual/en/function.soundex.php. 11 func Soundex(str string) string { 12 if str == "" { 13 panic("str: cannot be an empty string") 14 } 15 table := [26]rune{ 16 '0', '1', '2', '3', // A, B, C, D 17 '0', '1', '2', // E, F, G 18 '0', // H 19 '0', '2', '2', '4', '5', '5', // I, J, K, L, M, N 20 '0', '1', '2', '6', '2', '3', // O, P, Q, R, S, T 21 '0', '1', // U, V 22 '0', '2', // W, X 23 '0', '2', // Y, Z 24 } 25 last, code, small := -1, 0, 0 26 sd := make([]rune, 4) 27 // build soundex string 28 for i := 0; i < len(str) && small < 4; i++ { 29 // ToUpper 30 char := str[i] 31 if char < '\u007F' && 'a' <= char && char <= 'z' { 32 code = int(char - 'a' + 'A') 33 } else { 34 code = int(char) 35 } 36 if code >= 'A' && code <= 'Z' { 37 if small == 0 { 38 sd[small] = rune(code) 39 small++ 40 last = int(table[code-'A']) 41 } else { 42 code = int(table[code-'A']) 43 if code != last { 44 if code != 0 { 45 sd[small] = rune(code) 46 small++ 47 } 48 last = code 49 } 50 } 51 } 52 } 53 // pad with "0" 54 for ; small < 4; small++ { 55 sd[small] = '0' 56 } 57 return string(sd) 58 }