Rez Moss

Rez Moss

Personal Musings: A Blog for the Tech-Savvy and Curious Mind

Go's String Manipulation

Nov 2021

Go provides a rich set of tools for string manipulation, both in its standard library and through idiomatic patterns. Understanding these can greatly enhance your ability to work with text in Go.

Basic Operations

  1. Concatenation

    s := "Hello" + " " + "World"
  2. String Length

    len := len("Go")

Strings Package

The strings package offers powerful functions:

  1. Splitting

    parts := strings.Split("a,b,c", ",")
  2. Joining

    joined := strings.Join([]string{"a", "b", "c"}, "-")
  3. Contains and Index

    contains := strings.Contains("seafood", "foo")
    index := strings.Index("chicken", "ken")
  4. Trimming

    trimmed := strings.TrimSpace(" hello ")

Efficient String Building

For complex string building, use strings.Builder:

var b strings.Builder
for i := 0; i < 1000; i++ {
    fmt.Fprintf(&b, "%d", i)
}
result := b.String()

Rune Handling

Strings in Go are UTF-8 encoded. Use runes for Unicode characters:

for _, r := range "Hello, 世界" {
    fmt.Printf("%c ", r)
}

Format Strings

Use fmt.Sprintf for complex string formatting:

s := fmt.Sprintf("Pi: %.2f", math.Pi)

Regular Expressions

For complex pattern matching, use the regexp package:

matched, _ := regexp.MatchString(`\d+`, "123")

Mastering string manipulation in Go involves understanding these tools and knowing when to use each one. With practice, you’ll be able to handle text processing tasks efficiently and idiomatically in Go.