/
string.go
112 lines (92 loc) · 1.57 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
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
package utf16
type (
// Str is a UTF-16 encoded string
Str []uint16
)
func S(a string) Str {
return NewStr(a)
}
func NewStr(a string) Str {
return Encode(a)
}
func NewFromRunes(r []rune) Str {
return EncodeRunes(r)
}
// String is the UTF-8 string representation of Str
func (s Str) String() string {
return Decode(s)
}
// Contains checks if substr is inside s
func (s Str) Contains(substr Str) bool {
return s.Index(substr) >= 0
}
// Index the position of substr in s
func (s Str) Index(substr Str) int {
switch n := len(substr); {
case n == 0:
return 0
case n == 1:
for i := range s {
if s[i] == substr[0] {
return i
}
}
return -1
case n == len(s):
if s.Equal(substr) {
return 0
}
return -1
case n > len(s):
return -1
}
// brute force
var i, j int
for j < len(substr) && i < len(s) {
si := s[i]
bi := substr[j]
i++
if si == bi {
j++
} else {
j = 0
}
}
if j == len(substr) {
return i - len(substr)
}
return -1
}
// Equal checks if s is equal o
func (s Str) Equal(o Str) bool {
if len(s) != len(o) {
return false
}
for i := 0; i < len(s); i++ {
if s[i] != o[i] {
return false
}
}
return true
}
func (s Str) TrimPrefix(substr Str) Str {
if s.Index(substr) == 0 {
return Str(s[len(substr):])
}
return s
}
func (s Str) HasPrefix(substr Str) bool {
return s.Index(substr) == 0
}
func (s Str) Len() int {
return len(s)
}
func (s Str) Runes() []rune {
return DecodeRunes(s)
}
func (s Str) Append(o Str) Str {
return Str(append(s, o...))
}
func (s Str) Prepend(o Str) Str {
return Str(append(o, s...))
}