Go by Example

String Functions

Search, split, trim, replace, and build strings efficiently with the strings package.

The strings package searches, splits, joins, trims, and transforms strings. strings.Builder is useful when a loop appends many parts into one result.

Search and split text with strings functions, then use a builder to assemble a result without repeatedly creating larger strings.

package main
 
import (
    "fmt"
    "strings"
)
 
func main() {
    words := strings.Split("go is clear", " ")
    fmt.Println(strings.Contains(words[0], "g"))
    var result strings.Builder
    for i, word := range words {
        if i > 0 {
            result.WriteString(" ")
        }
        result.WriteString(word)
    }
    fmt.Println(result.String())
}

In production

A builder is useful when many writes form one string, but simple concatenation is fine for a few values. Strings are byte sequences, so use unicode-aware helpers or the utf8 package when operations must treat multi-byte characters as individual runes.

Enjoyed this? Get more software craft delivered to your inbox.