Accessing Characters in Golang Strings
In Go, accessing characters from a string differs from its ASCII counterpart, returning the underlying byte value instead of the character. As strings represent byte arrays, retrieving the first character results in its numerical ASCII representation. For instance, "HELLO"[1] returns 69 instead of the intended 'E.'
Solution: Converting to ASCII or Unicode Code Points
To obtain the actual character, consider employing the following techniques:
1. ASCII (Single-Byte Characters):
Convert the byte value to a string, effectively returning the ASCII character:
fmt.Println(string("Hello"[1])) // Prints "e"
2. Unicode (Multi-Byte Characters):
Convert the string to a slice of runes (Unicode code points) and access the desired position:
fmt.Println(string([]rune("Hello, 世界")[1])) // Prints "e" (ASCII) fmt.Println(string([]rune("Hello, 世界")[8])) // Prints "界" (UTF-8)
Additional Notes:
The above is the detailed content of How Do I Correctly Access Characters in Go Strings?. For more information, please follow other related articles on the PHP Chinese website!