-
Notifications
You must be signed in to change notification settings - Fork 4
/
strings.go
75 lines (61 loc) · 1.25 KB
/
strings.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
package utils
import (
"crypto/md5"
"fmt"
"io"
"strings"
)
type Strings string
func NewString(i interface{}) Strings {
s := Strings(fmt.Sprintf("%v", i))
return s
}
func (s Strings) String() string {
return string(s)
}
func (s Strings) Md5() string {
m := md5.New()
io.WriteString(m, s.String())
return fmt.Sprintf("%x", m.Sum(nil))
}
// convert like this: "HelloWorld" to "hello_world"
func (s Strings) SnakeCasedName() string {
newstr := make([]rune, 0)
firstTime := true
for _, chr := range string(s) {
if isUpper := 'A' <= chr && chr <= 'Z'; isUpper {
if firstTime == true {
firstTime = false
} else {
newstr = append(newstr, '_')
}
chr -= ('A' - 'a')
}
newstr = append(newstr, chr)
}
return string(newstr)
}
// convert like this: "hello_world" to "HelloWorld"
func (s Strings) TitleCasedName() string {
newstr := make([]rune, 0)
upNextChar := true
for _, chr := range string(s) {
switch {
case upNextChar:
upNextChar = false
chr -= ('a' - 'A')
case chr == '_':
upNextChar = true
continue
}
newstr = append(newstr, chr)
}
return string(newstr)
}
func (s Strings) PluralizeString() string {
str := string(s)
if strings.HasSuffix(str, "y") {
str = str[:len(str)-1] + "ie"
}
return str + "s"
}