Home >Backend Development >Golang >How Do I Correctly Access Characters in Go Strings?

How Do I Correctly Access Characters in Go Strings?

Patricia Arquette
Patricia ArquetteOriginal
2024-12-22 17:55:13207browse

How Do I Correctly Access Characters in Go Strings?

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:

  • For detailed insights, refer to the Go Programming Language Specification on Conversions.
  • For further exploration, check out "Strings, bytes, runes and characters in Go" on The Go Blog.

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn