-
Notifications
You must be signed in to change notification settings - Fork 0
/
strings.go
92 lines (79 loc) · 1.81 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
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
package strings
import (
"fmt"
"math/rand"
"strings"
"time"
)
var (
// Alphabets represents alphabet list, used for string generation
Alphabets = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
)
// init initializes the random number generator
func init() {
rand.Seed(time.Now().UTC().UnixNano())
}
// GetRandomString will generate a random string with given length
func GetRandomString(n int) string {
var bytes = make([]byte, n)
rand.Read(bytes)
for i, b := range bytes {
bytes[i] = Alphabets[b%byte(len(Alphabets))]
}
return string(bytes)
}
// GetRandomNumber will generate a random string with given length of numbers
func GetRandomNumber(width int) string {
numeric := [10]byte{0, 1, 2, 3, 4, 5, 6, 7, 8, 9}
r := len(numeric)
rand.Seed(time.Now().UnixNano())
var sb strings.Builder
for i := 0; i < width; i++ {
fmt.Fprintf(&sb, "%d", numeric[rand.Intn(r)])
}
return sb.String()
}
// SubString will return a sub string with given start position and length
func SubString(str string, start int, length int) string {
rs := []rune(str)
rl := len(rs)
end := 0
if start < 0 {
start = rl - 1 + start
}
end = start + length
if start > end {
start, end = end, start
}
if start < 0 {
start = 0
}
if start > rl {
start = rl
}
if end < 0 {
end = 0
}
if end > rl {
end = rl
}
return string(rs[start:end])
}
// ContainString will split string and query target string is splited array
func ContainString(source string, sep string, target string) bool {
for _, s := range strings.Split(source, sep) {
if s == target {
return true
}
}
return false
}
// ContainsInArray will query string array and check wether target is in array
func ContainsInArray(source []string, target string) bool {
for _, s := range source {
if s == target {
return true
}
}
return false
}