4.6 字符和字符串处理
一、理解rune类型
rune相当于go的char
func main() { // 定义初始值 s := "Yes我是北雪南星!" // 输出初始值长度 fmt.Println(len(s)) // 输出默认的内容 fmt.Printf("%s\n", []byte(s)) fmt.Printf("%x\n", []byte(s)) // 输出每个字符的内容 for _, b := range s { fmt.Printf("%x ", b) } fmt.Println() // 输出每个字符的内容 for i, ch := range s { // ch is a rune fmt.Printf("(%d %x)", i, ch) } fmt.Println() // 获取长度 fmt.Println(utf8.RuneCountInString(s)) // 通过utf8解密获取内容 bytes := []byte(s) for len(bytes) > 0 { ch, size := utf8.DecodeRune(bytes) bytes = bytes[size:] fmt.Printf("%c ", ch) } fmt.Println() // 通过rune转化成中文(每个子4字节) for i, ch := range []rune(s) { fmt.Printf("(%d, %c)", i, ch) } fmt.Println() }总结:
使用range遍历pos,rune对
使用utf8.RuneCountInString获取字符数
len获取字节数
使用[]byte获得字节
4.5例子改成支持中文:
func lengthOfNonRepeatingSubStr(s string) int { lastOccureed := make(map[rune]int) // 出现修改 start := 0 maxLength := 0 for i, ch := range []rune(s) { // 出现修改 lastI, ok := lastOccureed[ch] if ok && lastI >= start { start = lastOccureed[ch] + 1 } if i-start+1 > maxLength { maxLength = i - start + 1 } lastOccureed[ch] = i } return maxLength }备注:吧byte改变成rune
二、字符串的其他操作
strings.中有很多操作
字符串分开或合起来:Fields,Split,Join
查找子串:Contains,Index
全部大写,小写:ToLower,ToUpper
:Trim,TrimRight,TrimLeft
Last updated
Was this helpful?