CodeBlanks Logo Icon CodeBlanks

String concatenation

Learn string concatenation with + and fmt.Sprintf.

String concatenation

There are three common ways to join a few pieces:

ad, soyad := "Ada", "Lovelace"
tam := ad + " " + soyad                    // 1) the + operator
tam = fmt.Sprintf("%s %s", ad, soyad)       // 2) Sprintf
tam = strings.Join([]string{ad, soyad}, " ") // 3) Join

For a few pieces +, when formatting is needed Sprintf, and when joining a slice with a separator Join is the most readable.

strings.Builder

strings.Builder adds text piece by piece and produces a single string at the end:

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

Because Builder is an io.Writer, fmt.Fprintf can write to it directly; if the size is known, reserve room with b.Grow(n).

Practice List text

Join the slice meyveler := []string{"elma", "armut", "kiraz"} with strings.Join using the separator ", " and print it with fmt.Sprintf("%d meyve: %s", ...).

Starter code

main.go
package main

import (
    "fmt"
    "strings"
)

func main() {
    // buraya yaz
}

Sample solution

main.go
package main

import (
    "fmt"
    "strings"
)

func main() {
    meyveler := []string{"elma", "armut", "kiraz"}
    fmt.Println(fmt.Sprintf("%d meyve: %s", len(meyveler), strings.Join(meyveler, ", ")))
}

Expected output

3 meyve: elma, armut, kiraz

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 What is the most efficient way to join thousands of pieces in a loop?

  • Appending to a []rune
  • strings.Builder Correct answer
  • s += parca
  • fmt.Sprintf at every step

Explanation: Builder collects bytes in a growing buffer; += allocates and copies a new string at every step.

2 Join with a separator

Question
liste := strings.____([]string{"elma", "armut"}, ", ")
Answer
liste := strings.Join([]string{"elma", "armut"}, ", ")

Explanation: strings.Join joins slice elements with the given separator.

3 Method and use

Term Meaning
a + b A few pieces
fmt.Sprintf Formatted text
strings.Join Slice + separator
strings.Builder Many pieces in a loop

All lessons in Beginner