Character string indexing

String elements are of type byte and can be accessed using normal indexing operations.

How can I get a string element as char?

"some" [1] β†’ "o"

+6
source share
2 answers

The simplest solution is to convert it to an array of runes:

var runes = []rune("someString") 

Note that when you iterate over a string, you do not need a conversion. See this example from the Effective Way :

 for pos, char := range "ζ—₯本θͺž" { fmt.Printf("character %c starts at byte position %d\n", char, pos) } 

Will print

 character ζ—₯ starts at byte position 0 character 本 starts at byte position 3 character θͺž starts at byte position 6 
+10
source

Go strings are usually, but not necessarily, UTF-8 encoded. In case they are Unicode strings, the term "char [acter]" is quite complex and there is no general / unique bijection of runes (code points) and Unicode characters.

In any case, you can easily work with code points (runes) in a slice and use indices in it using a transformation:

 package main import "fmt" func main() { utf8 := "Hello, δΈ–η•Œ" runes := []rune(utf8) fmt.Printf("utf8:% 02x\nrunes: %#v\n", []byte(utf8), runes) } 

Also here: http://play.golang.org/p/qWVSA-n93o

Note. Often, the desire to access Unicode characters by index is a design error. Most text data is processed sequentially.

+4
source

All Articles