string.go 960 B

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647
  1. package util
  2. import (
  3. "math/rand"
  4. "time"
  5. "unicode/utf8"
  6. )
  7. // StrLen utf8 string length
  8. func StrLen(s string) int {
  9. return utf8.RuneCountInString(s)
  10. }
  11. // StrMax verify string's max lenth
  12. func StrMax(s string, max int) bool {
  13. n := utf8.RuneCountInString(s)
  14. return n <= max
  15. }
  16. // StrMin verify string's min lenth
  17. func StrMin(s string, min int) bool {
  18. n := utf8.RuneCountInString(s)
  19. return n >= min
  20. }
  21. // StrRange verify string's Range lenth
  22. func StrRange(s string, min, max int) bool {
  23. n := utf8.RuneCountInString(s)
  24. if n <= max && n >= min {
  25. return true
  26. }
  27. return false
  28. }
  29. // Random 指定长度的随机字符串(字母或数字)
  30. func Random(n int) string {
  31. str := "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
  32. bytes := []byte(str)
  33. result := []byte{}
  34. r := rand.New(rand.NewSource(time.Now().UnixNano()))
  35. n1 := len(bytes)
  36. for i := 0; i < n; i++ {
  37. result = append(result, bytes[r.Intn(n1)])
  38. }
  39. return string(result)
  40. }