-
Notifications
You must be signed in to change notification settings - Fork 0
/
string_utils.go
115 lines (98 loc) · 2.08 KB
/
string_utils.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
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
package go_commons
import (
cRand "crypto/rand"
"encoding/base64"
"regexp"
"strconv"
"strings"
)
func generateRandomBytes(n int) ([]byte, error) {
b := make([]byte, n)
_, err := cRand.Read(b)
// Note that err == nil only if we read len(b) bytes.
if err != nil {
return nil, err
}
return b, nil
}
func GenerateRandomString(s int) (string, error) {
b, err := generateRandomBytes(s)
return base64.URLEncoding.EncodeToString(b), err
}
func BoolToString(input bool) string {
return strconv.FormatBool(input)
}
func BytesToString(data []byte) string {
return string(data[:])
}
func Int64ToString(input int64) string {
return strconv.FormatInt(input, 10)
}
func StringToInt64(input string) (output int64, err error) {
if input == "" {
output = 0
err = nil
} else {
output, err = strconv.ParseInt(input, 0, 64)
}
return
}
func IsStringContainsAnyKeywords(s string, keywords []string) bool {
contain := false
for i := range keywords {
if strings.Contains(s, keywords[i]) {
contain = true
break
}
}
return contain
}
func StringTrimSpace(s string) string {
return strings.TrimSpace(s)
}
func IsStringEmpty(s string) bool {
return s == ""
}
func addWordBoundariesToNumbers(s string) string {
b := []byte(s)
b = numberSequence.ReplaceAll(b, numberReplacement)
return string(b)
}
var numberSequence = regexp.MustCompile(`([a-zA-Z])(\d+)([a-zA-Z]?)`)
var numberReplacement = []byte(`$1 $2 $3`)
func toCamelInitCase(s string, initCase bool) string {
s = addWordBoundariesToNumbers(s)
s = strings.Trim(s, " ")
n := ""
capNext := initCase
for _, v := range s {
if v >= 'A' && v <= 'Z' {
n += string(v)
}
if v >= '0' && v <= '9' {
n += string(v)
}
if v >= 'a' && v <= 'z' {
if capNext {
n += strings.ToUpper(string(v))
} else {
n += string(v)
}
}
if v == '_' || v == ' ' || v == '-' {
capNext = true
} else {
capNext = false
}
}
return n
}
func ToCamel(s string) string {
return toCamelInitCase(s, true)
}
func CensorString(str string) string {
if len(str) <= 6 {
return "***"
}
return str[:2] + "***" + str[len(str)-2:]
}