-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathwords.go
44 lines (40 loc) · 1.51 KB
/
words.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
package humanizer
import (
"strings"
"unicode"
)
// ToWords converts a string to a slice of words. For example:
//
// ToWords("The brown fox jumps over the fence") // []string{"The", "brown", "fox", "jumps", "over", "the", "fence"}
// ToWords("the_brown_fox_jumps_over_the_fence") // []string{"the", "brown", "fox", "jumps", "over", "the", "fence"}
// ToWords("the-brown-fox-jumps-over-the-fence") // []string{"the", "brown", "fox", "jumps", "over", "the", "fence"}
// ToWords("theBrownFoxJumpsOverTheFence") // []string{"the", "Brown", "Fox", "Jumps", "Over", "The", "Fence"}
// ToWords("TheBrownFoxJumpsOverTheFence") // []string{"The", "Brown", "Fox", "Jumps", "Over", "The", "Fence"}
func ToWords(value string) []string {
if value == "" {
return []string{}
}
var result []string
upper := false
sb := strings.Builder{}
for _, c := range value {
if (unicode.IsLetter(c) && unicode.IsUpper(c) && !upper) || unicode.IsDigit(c) || unicode.IsSymbol(c) || unicode.IsPunct(c) || unicode.IsSpace(c) {
if sb.Len() > 0 {
result = append(result, sb.String())
sb.Reset()
}
upper = true
}
if !unicode.IsLetter(c) || !unicode.IsUpper(c) {
upper = false
}
if !unicode.IsSymbol(c) && !unicode.IsPunct(c) && !unicode.IsSpace(c) {
sb.WriteRune(c)
}
}
if sb.Len() > 0 {
result = append(result, sb.String())
sb.Reset()
}
return result
}