string.go 1018 B

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
  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. if n <= max {
  15. return true
  16. }
  17. return false
  18. }
  19. // StrMin verify string's min lenth
  20. func StrMin(s string, min int) bool {
  21. n := utf8.RuneCountInString(s)
  22. if n >= min {
  23. return true
  24. }
  25. return false
  26. }
  27. // StrRange verify string's Range lenth
  28. func StrRange(s string, min, max int) bool {
  29. n := utf8.RuneCountInString(s)
  30. if n <= max && n >= min {
  31. return true
  32. }
  33. return false
  34. }
  35. // Random 指定长度的随机字符串(字母或数字)
  36. func Random(n int) string {
  37. str := "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
  38. bytes := []byte(str)
  39. result := []byte{}
  40. r := rand.New(rand.NewSource(time.Now().UnixNano()))
  41. n1 := len(bytes)
  42. for i := 0; i < n; i++ {
  43. result = append(result, bytes[r.Intn(n1)])
  44. }
  45. return string(result)
  46. }