Home >Backend Development >Golang >How to Efficiently Access and Convert Characters in Go Strings?

How to Efficiently Access and Convert Characters in Go Strings?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-12-19 06:22:13781browse

How to Efficiently Access and Convert Characters in Go Strings?

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:

  • [Go Programming Language Specification section on Conversions](https://go.dev/ref/spec#Conversions)
  • [The Go Blog: Strings, bytes, runes and characters in Go](https://blog.golang.org/strings-bytes-runes-and-characters-in-go)

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!

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