GoGo

Go: Strings – code examples

Contents

Count words

Strings#map#fields#text#counting
Use case: Text analysis, e.g. the most frequent words in a document.
package main

import (
	"fmt"
	"strings"
)

func main() {
	text := "this is a test this is good"
	zaehler := map[string]int{}
	for _, w := range strings.Fields(text) {
		zaehler[w]++
	}
	fmt.Println(zaehler) // map[a:1 good:1 is:2 test:1 this:2]
}

Missing map keys yield 0, so zaehler[w]++ is enough. fmt prints maps sorted by key. strings.Fields splits on any whitespace.

Regular expression

Strings#regexp#pattern#regex
Use case: Find email addresses, phone numbers or patterns in text.
package main

import (
	"fmt"
	"regexp"
)

func main() {
	text := "Contact: ada@example.com, bob@test.org"
	re := regexp.MustCompile(`[\w.]+@[\w.]+\.\w+`)
	fmt.Println(re.FindAllString(text, -1)) // [ada@example.com bob@test.org]

	ziffern := regexp.MustCompile(`\d+`)
	fmt.Println(ziffern.ReplaceAllString("Phone 12345", "#")) // Phone #
}

Raw strings in backticks save doubled backslashes. MustCompile aborts on an invalid pattern (ideal for fixed patterns); Go uses the RE2 syntax without backreferences.

Manipulate strings

Strings#strings#builder#split#join
Use case: Clean up input, split and assemble text.
package main

import (
	"fmt"
	"strings"
)

func main() {
	s := "  Go is fun  "
	fmt.Println(strings.ToLower(strings.TrimSpace(s)))              // go is fun
	fmt.Println(strings.Join(strings.Split("x,y,z", ","), "-"))      // x-y-z
	fmt.Println(strings.Replace("Python", "y", "Y", 1), strings.HasPrefix("abc", "a")) // PYthon true

	var sb strings.Builder
	for i := 1; i <= 3; i++ {
		fmt.Fprintf(&sb, "%d;", i)
	}
	fmt.Println(sb.String()) // 1;2;3;
}

Strings are immutable; strings.Builder assembles text efficiently. A string consists of bytes (UTF-8): len("ß") is 2 – for characters use []rune(s).