๐ŸŽ“ A1Learner
๐Ÿ”
0 of 34 lessons completed

Go Strings in Depth

Strings in depth is the study of how text is stored and built. A Go string is a sequence of bytes.

A Builder joins the parts

strings.Builder collects parts in order. String returns the joined text and Len reports its length in bytes.

package main

import (
	"fmt"
	"strings"
)

func main() {
	var b strings.Builder
	b.WriteString("Go")
	b.WriteString(" is")
	b.WriteString(" fun")
	fmt.Println(b.String())
	fmt.Println(b.Len())
}

Runes count characters

The word cafรฉ has one accented letter. That letter takes two bytes but counts as one rune.

package main

import "fmt"

func main() {
	word := "cafรฉ"
	fmt.Println(len(word))
	fmt.Println(len([]rune(word)))
}

Fields and Join clean a line

Fields splits a messy line into its words. Join puts the words back with one space between them.

package main

import (
	"fmt"
	"strings"
)

func main() {
	line := "Go   is    fun"
	words := strings.Fields(line)
	fmt.Println(strings.Join(words, " "))
	fmt.Println(len(words))
}

TrimSpace first, then ReplaceAll

TrimSpace cuts spaces from both ends of a string. ReplaceAll then swaps every match in the result.

package main

import (
	"fmt"
	"strings"
)

func main() {
	text := "  cat cat  "
	clean := strings.ReplaceAll(strings.TrimSpace(text), "cat", "dog")
	fmt.Println(clean)
	fmt.Println(len(clean))
}

Example

package main

import (
	"fmt"
	"strings"
)

func main() {
	var b strings.Builder
	b.WriteString("Hana")
	b.WriteString(" - ")
	b.WriteString("Level ")
	b.WriteString("3")
	fmt.Println(b.String())
	fmt.Println(b.Len())
}

Key points

  • len on a string counts bytes, not characters.
  • A byte is one small unit of storage.
  • A rune holds one character of text.
  • Converting a string to []rune gives one rune per character.
  • strings.Builder collects parts and joins them into one string.

In this example, a Builder collects four parts in order. The parts spell a name tag for Hana at level 3. String returns the joined tag, and Len reports 14 bytes.

Note

Strings never change in place, so each cleaning step returns a new string.

Try it Yourself

Edit the code, then press Run.

Running is simulated ยท Go Playground

Exercise

What does len([]rune("cafรฉ")) give?