Problem Solving with Go course

Reading InputSplitting Lines: Fields, Split and Cut

Problem Solving with Go

Display

Theme

Reading Input · Test exercise

Splitting Lines: Fields, Split and Cut

Once you have a line, you need to break it into parts. The strings package has three tools you'll reach for most often.

strings.Fields: split on spaces

Fields splits a string at every run of spaces (tabs included), and never produces empty parts:

strings.Fields("  3   x 12000 ") // ["3" "x" "12000"]

It suits input whose columns are separated by spaces, however many spaces there are.

strings.Split: split on an exact separator

Split breaks the string at every occurrence of the separator, exactly. Two separators side by side leave an empty string between them:

strings.Split("4,8,,15", ",") // ["4" "8" "" "15"]
strings.Split("a b", " ")     // ["a" "b"]
strings.Split("a  b", " ")    // ["a" "" "b"]

Use Split for separators like a comma or "\n", and Fields for spaces.

strings.Cut: split only once

Often a line has the shape key: value, and the key itself may contain spaces. Cut cuts at the first occurrence of the separator and tells you whether it found it:

item, rest, found := strings.Cut("green tea: 3 x 12000", ": ")
// item = "green tea", rest = "3 x 12000", found = true

If found is false, the line doesn't match the format. Don't ignore it: return an error.

Check the shape before you index

fields[2] on a slice with only two elements panics. Check len(fields) first, then convert the numbers with strconv.Atoi and handle the error.

Task

A small shop logs orders in the format <item>: <qty> x <price>, for example green tea: 3 x 12000. An item's name can be several words long.

  1. Complete parseOrder(line string) (Order, error). Cut with strings.Cut(line, ": "), then split the rest with strings.Fields. The rest must be exactly three parts with x in the middle. Return an error if there's no ": ", if the number of parts is wrong, or if the quantity and price aren't whole numbers.
  2. Complete total(input string) (int, error): add up Qty * Price for every line that isn't blank. If any line is wrong, return its error.
main.go
package main

import (
	"fmt"
	"io"
	"os"
)

type Order struct {
	Item  string
	Qty   int
	Price int
}

// parseOrder reads one line such as "green tea: 3 x 12000".
func parseOrder(line string) (Order, error) {
	// TODO: split on ": " with strings.Cut, then use strings.Fields on the rest
	return Order{}, nil
}

// total adds up Qty * Price for every non-empty line of the input.
func total(input string) (int, error) {
	// TODO
	return 0, nil
}

func main() {
	data, err := io.ReadAll(os.Stdin)
	if err != nil {
		fmt.Println("could not read input:", err)
		return
	}
	sum, err := total(string(data))
	if err != nil {
		fmt.Println("bad input:", err)
		return
	}
	fmt.Println("total:", sum)
}
Go runtime not loaded yet

4 lines · 81 B of the 1 MB limit. Submit always uses the lesson's own input.