-
-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathstringutil.go
81 lines (65 loc) · 1.76 KB
/
stringutil.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
package main
import (
"sort"
"strconv"
"strings"
"unicode/utf8"
)
// AddLastRune will check the last rune of a string,
// if the last rune does not match, it will append the rune,
// and return the fixed string
func AddLastRune(str string, rune rune) (fixed string) {
fixed = str
r, _ := utf8.DecodeLastRuneInString(str)
if r != rune {
fixed = str + string(rune)
}
return fixed
}
// RemoveLastRune removes rune from str if str ends with rune
func RemoveLastRune(str string, rune rune) (fixed string) {
fixed = str
r, _ := utf8.DecodeLastRuneInString(str)
if r == rune {
fixed = TrimLastRune(str)
}
return fixed
}
// RemoveFirstRune removes rune from str if str begins with rune
func RemoveFirstRune(str string, rune rune) (fixed string) {
fixed = str
r, _ := utf8.DecodeRuneInString(str)
if r == rune {
fixed = TrimFirstRune(str)
}
return fixed
}
// TrimFirstRune will remove the first rune in a string
func TrimFirstRune(s string) string {
_, i := utf8.DecodeRuneInString(s)
return s[i:]
}
// TrimLastRune will remove the last rune in a string
func TrimLastRune(s string) string {
s = s[:len(s)-1]
return s
}
func Grammar(amount int, singular string, multiple string) string {
if amount != 1 {
return strings.Join([]string{strconv.Itoa(amount), multiple}, " ")
} else {
return strings.Join([]string{strconv.Itoa(amount), singular}, " ")
}
}
// TODO: This breaks if the string is empty
// LastByte returns the last byte of a byte array
// and also returns the string as a byte array
func LastByte(s string) (byte, []byte) {
b := []byte(s)
return b[len(b)-1], b
}
// Contains TODO: This breaks if the slice contains blank spaces
func Contains(s []string, term string) bool {
i := sort.SearchStrings(s, term)
return i < len(s) && s[i] == term
}