4 ms·
> if you iterate over a Go string using "range", you get 32-bit "runes" It's often easier to use that for-loop with a break to look at the first character of s
by vorg 10y ago
> if you iterate over a Go string using "range", you get 32-bit "runes"
It's often easier to use that for-loop with a break to look at the first character of such a string, as in...
package main
import "fmt"
func main(){
str:= "我是一个人"
for _, r:= range str {
fmt.Printf("%c\n", r)
break
}
}
Doing a str[0] prints the first utf8 byte of the string ("æ") instead of the whole character. The name of the official function is difficult to remember, and you have to put an import at the top...
import "unicode/utf8"
...
r, _:= utf8.DecodeRuneInString(str)