string.go 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. package buildin
  2. import (
  3. "fmt"
  4. "math/rand"
  5. "time"
  6. "unicode/utf8"
  7. "unsafe"
  8. )
  9. const (
  10. // 6 bits to represent a letter index
  11. letterIdBits = 6
  12. // All 1-bits as many as letterIdBits
  13. letterIdMask = 1<<letterIdBits - 1
  14. letterIdMax = 63 / letterIdBits
  15. )
  16. // SplitStringByLength 将字符串按长度划分为数组,汉字2个长度英文1个长度
  17. func SplitStringByLength(str string, maxLength int) []string {
  18. var arr []string
  19. index := 0
  20. s := ""
  21. for _, v := range str {
  22. s = s + string(v)
  23. if utf8.RuneLen(v) == 1 {
  24. index += 1
  25. } else {
  26. index += 2
  27. }
  28. if index >= maxLength {
  29. arr = append(arr, s)
  30. index = 0
  31. s = ""
  32. }
  33. }
  34. if s != "" {
  35. arr = append(arr, s)
  36. }
  37. return arr
  38. }
  39. // RandString 随机生成字符串 最强性能!
  40. func RandString(n int) string {
  41. letters := "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"
  42. var src = rand.NewSource(time.Now().UnixNano())
  43. b := make([]byte, n)
  44. // A rand.Int63() generates 63 random bits, enough for letterIdMax letters!
  45. for i, cache, remain := n-1, src.Int63(), letterIdMax; i >= 0; {
  46. if remain == 0 {
  47. cache, remain = src.Int63(), letterIdMax
  48. }
  49. if idx := int(cache & letterIdMask); idx < len(letters) {
  50. b[i] = letters[idx]
  51. i--
  52. }
  53. cache >>= letterIdBits
  54. remain--
  55. }
  56. return *(*string)(unsafe.Pointer(&b))
  57. }
  58. // RandNumberString 返回特定长度的数据随机数字字符串
  59. func RandNumberString(bit uint8) string {
  60. rand.Seed(time.Now().UnixNano())
  61. s := ""
  62. for i := 0; uint8(i) < bit; i++ {
  63. r := rand.Intn(9)
  64. s += fmt.Sprintf("%d", r)
  65. }
  66. return s
  67. }