CodeBlanks Logo Icon CodeBlanks

Summary - String

Combine strconv and strings to write a text processor.

Strings summary

Strings are immutable UTF-8 bytes: len counts bytes, range and []rune work with characters. Joining: +, Sprintf, Join, and strings.Builder in loops. Conversion: strconv.Atoi/Itoa/ParseFloat (check the errors). Searching and editing: strings.Contains, HasPrefix, Split, Fields, Replace, TrimSpace, EqualFold.

strings.Cut

strings.Cut, added in Go 1.18, splits a text in two at the first separator; it is very handy for parsing key=value pairs:

anahtar, deger, bulundu := strings.Cut("port=8080", "=")
fmt.Println(anahtar, deger, bulundu)  // port 8080 true

If there is no separator, bulundu is false and the whole text goes to anahtar.

Practice Settings parser

Split the text "ad=Ada;yas=36;dil=go" on ; with strings.Split, then cut each piece on = with strings.Cut and put it into a map[string]string. Print m["dil"] and len(m).

Starter code

main.go
package main

import (
    "fmt"
    "strings"
)

func main() {
    // buraya yaz
}

Sample solution

main.go
package main

import (
    "fmt"
    "strings"
)

func main() {
    m := map[string]string{}
    for _, parca := range strings.Split("ad=Ada;yas=36;dil=go", ";") {
        if k, v, ok := strings.Cut(parca, "="); ok {
            m[k] = v
        }
    }
    fmt.Println(m["dil"], len(m))
}

Expected output

go 3

Questions and answers

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

1 What is the difference between <code>strings.Split("a b", " ")</code> and <code>strings.Fields("a b")</code>?

  • Split drops spaces
  • Split produces an empty piece ([a b], 3 elements), Fields doesn't ([a b]) Correct answer
  • They are the same
  • Fields errors

Explanation: Split cuts at every separator, leaving an empty string between two spaces. Fields treats consecutive spaces as one separator.

2 Split at the first separator

Question
k, v, ok := strings.____("ad=Ada", "=")
Answer
k, v, ok := strings.Cut("ad=Ada", "=")

Explanation: Cut splits the text into two parts at the first separator and says whether it was found.

3 Group summary

Term Meaning
len(s) Byte count
[]rune(s) Characters
strconv.Atoi Number from text
strings.Builder Efficient joining

All lessons in Beginner