MMMHUHU
看看这个代码:package mainimport ( "fmt" "math/rand" "time")func init() { rand.Seed(time.Now().UnixNano())}var alphabet = []rune{ 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', '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', 'U', 'V', 'W', 'X', 'Y', 'Z', 'Æ', 'Ø', 'Å',}func randomString(n int) string { b := make([]rune, n, n) for k, _ := range b { b[k] = alphabet[rand.Intn(len(alphabet))] } return string(b)}const ( chunkSize int = 100 lead4Mask byte = 0xF8 // must equal 0xF0 lead3Mask byte = 0xF0 // must equal 0xE0 lead2Mask byte = 0xE0 // must equal 0xC0 lead1Mask byte = 0x80 // must equal 0x00 trailMask byte = 0xC0 // must equal 0x80)func longestPrefix(s string, n int) int { for i := (n - 1); ; i-- { if (s[i] & lead1Mask) == 0x00 { return i + 1 } if (s[i] & trailMask) != 0x80 { return i } } panic("never reached")}func main() { s := randomString(100000) for len(s) > chunkSize { cut := longestPrefix(s, chunkSize) fmt.Println(s[:cut]) s = s[cut:] } fmt.Println(s)}我正在使用丹麦语/挪威语字母表生成 100000 个符文的随机字符串。然后,“魔法”就在longestPrefix. 为了帮助您进行位移位部分,请参考下图:程序打印出各自最长的可能块 <= chunkSize,每行一个。