Skip to content

Instantly share code, notes, and snippets.

@arloor
Created June 11, 2024 12:13
Show Gist options
  • Save arloor/fea5502d4ffc617c4d82083f6b642b43 to your computer and use it in GitHub Desktop.
Save arloor/fea5502d4ffc617c4d82083f6b642b43 to your computer and use it in GitHub Desktop.
生成随机中文字符串
package main
import (
"fmt"
"math/rand"
"time"
"unicode/utf8"
)
const letterBytes = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"
const chineseChars = "汉字中文字符"
func RandStringBytes(n int) string {
b := make([]byte, n)
for i := range b {
b[i] = letterBytes[rand.Intn(len(letterBytes))]
}
return string(b)
}
func RandStringChinese(n int) string {
b := make([]rune, n)
for i := range b {
b[i] = []rune(chineseChars)[rand.Intn(utf8.RuneCountInString(chineseChars))]
}
return string(b)
}
func main() {
rand.Seed(time.Now().UnixNano())
strings := make([]string, 20)
for i := range strings {
length := rand.Intn(21) + 30 // 随机长度在 30-50
if i < 5 {
strings[i] = RandStringChinese(length)
} else {
strings[i] = RandStringBytes(length)
}
}
for _, str := range strings {
fmt.Println(str)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment