Ben Chuanlong Du's Blog

It is never too late to learn.

String in Golang

Things on this page are fragmentary and immature notes/thoughts of the author. Please read with your own judgement!

Tips and Traps

  1. string is a primitive type in Golang, which means a string value has no methods on it but instead you have to use built-in functions (e.g., len) or functions in other modules (e.g., the strings module) to manipulate strings.

  2. Raw string literals, delimited by backticks (back quotes), are interpreted literally. They can contain line breaks, and backslashes have no special meaning.

  3. The built-in function len returns the length of bytes of a string. It is not necessary the length of unicode characters. For example, calling len on a Chinese character returns 3 instead of 1.

In [8]:
import "strings"
import "fmt"
import "strconv"
import "reflect"

Backtick / Multi-line Strings

In [2]:
s := `this is
a multiline
    string`
s
Out[2]:
this is
a multiline
    string

Slicing of Strings

In [2]:
s := "how are you"
s
Out[2]:
how are you

Each element of a string is a unsigned 8-bit integer (since Golang uses the UTF-8 encoding for strings). Notice it might or might not correspond to a character in the original string since an UTF-8 character might use up to 4 bytes.

In [10]:
s[0]
Out[10]:
104
In [11]:
reflect.TypeOf(s[0])
Out[11]:
uint8
In [6]:
s[:]
Out[6]:
how are you
In [4]:
s[2:]
Out[4]:
w are you
In [3]:
s[2:6]
Out[3]:
w ar
In [15]:
strconv.Itoa(2)
Out[15]:
2
In [17]:
strconv.Atoi("20")
Out[17]:
20 <nil>

Concatenate Strings

In [5]:
"how " + "are"
Out[5]:
how are
In [10]:
"how " + 2
Out[10]:
how how 
In [9]:
"how " * 2
invalid binary operation "how " * 2
In [19]:
"how " + strconv.Itoa(2)
Out[19]:
how 2

Concatenate/Join an Array of Strings

Please refer to Manipulate Strings Using the strings Module in Golang for more discussions.

Comparing Strings

Convert Integers to Strings

In [6]:
import "fmt"
import "strconv"
In [8]:
fmt.Sprintf("%d", 1)
Out[8]:
1
In [7]:
strconv.Itoa(1)
Out[7]:
1

Convert Strings to Integers

In [12]:
i, err := strconv.ParseInt("1", 10, 64)
i
Out[12]:
1

The strings Module

Please refer to Manipulate Strings Using the strings Module in Golang for detailed discussions.

Format Strings

Please refer to Format Strings in Golang for detailed discussions.

Strings in Golang Are UTF-8

Please refer to Strings in Golang Are UTF-8 for detailed discussions.

In [ ]:
 

Comments