Sobes.tech
Junior — Middle

How can you access characters or substrings within a string in Go?

sobes.tech AI

Answer from AI

In the Go language, strings are immutable sequences of bytes. To access characters or substrings, you can use byte slices or rune slices.

  1. Accessing bytes via indexing:
s := "hello"
byteValue := s[1] // 'e' as a byte
  1. For Unicode characters, it's better to convert the string to a rune slice:
s := "привет"
runes := []rune(s)
char := runes[1] // second character 'р'
  1. Getting substrings via slices:
s := "hello"
substr := s[1:4] // "ell"

It's important to remember that byte indexing can lead to incorrect handling of multi-byte Unicode characters, so for such cases, rune slices are preferable.

How can you access characters or substrings within a… - sobes.tech