Character Indexing in Golang Strings
Go strings are represented as sequences of bytes in UTF-8 encoding. To access individual characters, which may occupy multiple bytes, one can leverage the string or []rune conversion.
Accessing ASCII Characters
In the example:
fmt.Print("HELLO"[1])
The character at index 1 of the string "HELLO" is accessed. Since ASCII characters occupy only one byte, the result is the byte value 69.
Converting Bytes to Characters
To obtain the actual character value, the byte can be converted to a string. This ensures proper UTF-8 handling:
fmt.Println(string("Hello"[1])) // ASCII only
Accessing Unicode Characters
For Unicode characters, which can span multiple bytes, the []rune conversion is required:
fmt.Println(string([]rune("Hello, 世界")[1])) // UTF-8
Converting Runes to Bytes
To convert a rune back to a byte slice, it can be passed as an argument to []byte:
fmt.Println(string([]byte("Hello"))) // ASCII only
References:
The above is the detailed content of How to Efficiently Access and Convert Characters in Go Strings?. For more information, please follow other related articles on the PHP Chinese website!