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 changes text. A strings.Builder collects pieces of text efficiently when a loop needs to create a long 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; simple + concatenation is fine for a few values. A string stores bytes, so use strings or unicode/utf8 functions when your code must handle a multi-byte text symbol as one rune, Go's value for one Unicode code point.

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