-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathstring.go
More file actions
110 lines (94 loc) · 2.13 KB
/
string.go
File metadata and controls
110 lines (94 loc) · 2.13 KB
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
package stringx
import (
"strings"
"unicode/utf8"
)
// Len returns the actual character length of the string, not the byte length.
func Len(s string) int {
return utf8.RuneCountInString(s)
}
// Reverse reverses the string.
func Reverse(s string) string {
if len(s) <= 1 {
return s
}
var (
r rune
size int
)
b := strings.Builder{}
for i := len(s); i > 0; i -= size {
r, size = utf8.DecodeLastRuneInString(s[:i])
b.WriteRune(r)
}
return b.String()
}
// PadLeft pads the string on the left with the specified padding string until it reaches the desired length.
func PadLeft(s string, length int, padding string) string {
return pad(s, length, padding, -1)
}
// PadRight pads the string on the right with the specified padding string until it reaches the desired length.
func PadRight(s string, length int, padding string) string {
return pad(s, length, padding, 1)
}
// PadBoth pads the string on both sides with the specified padding string until it reaches the desired length.
func PadBoth(s string, length int, padding string) string {
return pad(s, length, padding, 0)
}
func pad(s string, length int, padding string, kind int) string {
if len(padding) == 0 {
return s
}
slen := Len(s)
if slen >= length {
return s
}
var leftLen, rightLen int
switch {
case kind < 0:
// pad left
leftLen = length - slen
case kind > 0:
// pad right
rightLen = length - slen
default:
// pad both
leftLen = (length - slen) / 2
rightLen = length - slen - leftLen
}
plen := Len(padding)
leftRepeat := leftLen / plen
rightRepeat := rightLen / plen
leftRemain := leftLen % plen
rightRemain := rightLen % plen
b := strings.Builder{}
if leftRepeat > 0 {
b.WriteString(strings.Repeat(padding, leftRepeat))
}
if leftRemain > 0 {
count := 0
for _, r := range padding {
if count < leftRemain {
b.WriteRune(r)
count++
} else {
break
}
}
}
b.WriteString(s)
if rightRepeat > 0 {
b.WriteString(strings.Repeat(padding, rightRepeat))
}
if rightRemain > 0 {
count := 0
for _, r := range padding {
if count >= rightRemain {
break
}
b.WriteRune(r)
count++
}
}
return b.String()
}