You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 

70 lines
1.6 KiB

package util
import (
"fmt"
"math/rand"
"regexp"
"strings"
"time"
)
// 生成随机数字字符串
func RandomNumberStr(length int) string {
nums := [10]byte{0, 1, 2, 3, 4, 5, 6, 7, 8, 9}
r := len(nums)
rand.Seed(time.Now().UnixNano())
var sb strings.Builder
for i := 0; i < length; i++ {
// 短信验证码第一位不能是0
if i == 0 {
fmt.Fprintf(&sb, "%d", nums[1:r][rand.Intn(r-1)])
} else {
fmt.Fprintf(&sb, "%d", nums[rand.Intn(r)])
}
}
return sb.String()
}
func RandStr(size int) string {
src := []string{"1", "2", "3", "4", "5", "6", "7", "8", "8", "0",
"a", "b", "c", "d", "e", "f", "g", "h", "i", "j",
"k", "l", "m", "n", "o", "p", "q", "r", "s", "t",
"y", "v", "w", "x", "y", "z",
"A", "B", "C", "D", "E", "F", "G", "H", "I", "J",
"K", "L", "M", "N", "O", "P", "Q", "R", "S", "T",
"Y", "V", "W", "X", "Y", "Z"}
var res []string
for i := 0; i < size; i++ {
res = append(res, src[rand.Int31n(62)])
}
return strings.Join(res, "")
}
func NotEmpty(v interface{}) bool {
return v != nil && v != ""
}
func CompressStr(str string) string {
if str == "" {
return ""
}
//匹配一个或多个空白符的正则表达式
reg := regexp.MustCompile("\\s+")
return reg.ReplaceAllString(str, "")
}
// 通过map主键唯一的特性过滤重复元素
func RemoveRepByMap(slc []string) []string {
result := []string{}
tempMap := map[string]byte{} // 存放不重复主键
for _, e := range slc {
if e != "" {
l := len(tempMap)
tempMap[e] = 0
if len(tempMap) != l { // 加入map后,map长度变化,则元素不重复
result = append(result, e)
}
}
}
return result
}