Go String Operations
Go supports multiple languages.
rune
is Go’s char
Let’s play with the string
1 | package main |
The outputs will be:
1 | Go is so cool! |
We could use utf8.DecodeRune
method to decode each rune.
1 | bytes := []byte(s) |
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 | for i, ch := range []rune(s) { |
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