Go String Operations

Go supports multiple languages.

rune is Go’s char

Let’s play with the string

1
2
3
4
5
6
7
8
9
10
11
12
13
package main

import "fmt"

func main() {
s := "Go is so cool!"
fmt.Println(s)
fmt.Println(len(s))

for i, ch := range s {
fmt.Printf("(%d, %X)", i, ch)
}
}

The outputs will be:

1
2
3
Go is so cool!
14
(0, 47)(1, 6F)(2, 20)(3, 69)(4, 73)(5, 20)(6, 73)(7, 6F)(8, 20)(9, 63)(10, 6F)(11, 6F)(12, 6C)(13, 21)

We could use utf8.DecodeRune method to decode each rune.

1
2
3
4
5
6
bytes := []byte(s)
for len(bytes) > 0 {
ch, size := utf8.DecodeRune(bytes)
bytes = bytes[size:]
fmt.Printf("%c ", ch)
}

The outputs will be:

1
G o   i s   s o   c o o l !

In the code for i, ch := range s, i is the address for each byte, which might be confusing.

We could use the following code instead:

1
2
3
for i, ch := range []rune(s) {
fmt.Printf("(%d, %c)", i, ch)
}

The outputs will be:

1
(0, G)(1, o)(2,  )(3, i)(4, s)(5,  )(6, s)(7, o)(8,  )(9, c)(10, o)(11, o)(12, l)(13, !)

string Package

In Go, there’s a string package with all the common string operations, e.g.

  • Fields, Split, Join
  • Contains, Index
  • ToLower, ToUpper
  • Trim, TrimRight, TrimLeft