1 截取普通字符串 - 直接當成數組切片
str := "XHelloWorldX" content := str[1 : len(str)-1] fmt.Println(content)
或者 - 轉換為數組(有聲明內部變量)切片
s := "abcdefg" s = string([]byte(s)[:3]) fmt.Println(s) //得到 "abc"
2 截取帶中文字符串
一個中文字符肯定不止一個字節,難道我還得遍歷每個字節,判斷編碼,那也太麻煩了吧。 我們不需要考慮那么多,除了byte還有另外一個類型rune,使用它完全不用考慮unicode字節問題,一個中文就只占一個數組下標。
str := "a中文cd" str = string([]rune(str)[:4]) fmt.Println(str)
轉載自:
https://juejin.im/post/5c8a45dee51d455bb15c2045 https://blog.csdn.net/zf766045962/article/details/90383377