-
Notifications
You must be signed in to change notification settings - Fork 4
/
string.go
57 lines (50 loc) · 1.36 KB
/
string.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
// 字符串相关方法封装
package goutils
import (
"regexp"
"strings"
"github.com/antlabs/strsim"
)
// RemoveAllWhitespace 删除字符串中所有的空白符
func RemoveAllWhitespace(s string) string {
s = strings.Replace(s, "\t", "", -1)
s = strings.Replace(s, "\n", "", -1)
s = strings.Replace(s, " ", "", -1)
return s
}
// ReverseString 翻转字符串
func ReverseString(s string) string {
r := []rune(s)
for i, j := 0, len(r)-1; i < len(r)/2; i, j = i+1, j-1 {
r[i], r[j] = r[j], r[i]
}
return string(r)
}
// RemoveDuplicateWhitespace 删除字符串中重复的空白字符为单个空白字符
// trim: 是否去掉首位空白
func RemoveDuplicateWhitespace(s string, trim bool) string {
ws, err := regexp.Compile(`\s+`)
if err != nil {
return s
}
s = ws.ReplaceAllString(s, " ")
if trim {
s = strings.TrimSpace(s)
}
return s
}
// StrSimilarity 提供不同的算法检测文本相似度
func StrSimilarity(s1, s2 string, algorithm string) float64 {
// strsim: 完全相同返回 1,完全不同返回 0
switch strings.ToLower(algorithm) {
case "levenshtein":
return strsim.Compare(s1, s2)
case "dice":
return strsim.Compare(s1, s2, strsim.DiceCoefficient())
case "jaro":
return strsim.Compare(s1, s2, strsim.Jaro())
case "hamming":
return strsim.Compare(s1, s2, strsim.Hamming())
}
return strsim.Compare(s1, s2, strsim.Hamming())
}