Go course

Packages and ModulesStandard Library: strings and strconv

Go

Display

Theme

Packages and Modules · Test exercise

Standard Library: strings and strconv

Go has a rich standard library. Here are two packages you'll use almost every time you work with text:

The strings package

strings.TrimSpace("  halo  ")            // "halo"
strings.ToLower("KoPi")                  // "kopi"
strings.ToUpper("kopi")                  // "KOPI"
strings.Contains("es kopi", "kopi")      // true
strings.HasPrefix("INV-001", "INV-")     // true
strings.Split("a,b,c", ",")              // []string{"a", "b", "c"}
strings.Fields("  satu  dua   tiga ")    // []string{"satu", "dua", "tiga"}
strings.Join([]string{"a", "b"}, "-")    // "a-b"
strings.ReplaceAll("a.b.c", ".", "/")    // "a/b/c"
strings.Repeat("=", 5)                   // "====="

A really useful function for splitting kunci=nilai (key=value) text is strings.Cut:

sebelum, sesudah, ketemu := strings.Cut("latte:2", ":")
// sebelum = "latte", sesudah = "2", ketemu = true

It returns the part before the separator, the part after it, and whether it was found. If the separator isn't found, ketemu is false.

The strconv package

strconv converts between strings and numbers:

n, err := strconv.Atoi("42")      // string -> int: 42, nil
_, err = strconv.Atoi("empat")    // error: invalid syntax

s := strconv.Itoa(42)             // int -> string: "42"

f, err := strconv.ParseFloat("3.5", 64) // string -> float64
b, err := strconv.ParseBool("true")     // string -> bool

Watch out: string(65) is not "65"; it's "A" (the character with code 65). To turn a number into its digits as text, always use strconv.Itoa or fmt.Sprint.

The Parse.../Atoi functions return an error, so handle it the way you learned in Chapter 7.

Task

A coffee shop's cashier receives orders as text like " Latte : 2 ". Complete:

  1. parsePesanan(baris string) (string, int, error):
    • split the text on : using strings.Cut; if there's no :, return an error,
    • menu item name: trim the spaces at the edges and convert it to lowercase,
    • quantity: trim the spaces at the edges, then convert with strconv.Atoi; if that fails, return an error,
    • if the name is empty or the quantity is <= 0, return an error.
    • If an error occurs, return "", 0, err.
  2. formatStruk(nama string, jumlah int) string returns "<jumlah>x <NAMA HURUF BESAR>", that is, the quantity, an x, and the name in uppercase. For example, formatStruk("latte", 2) becomes "2x LATTE". Use strconv.Itoa and strings.ToUpper.
main.go
package main

import (
	"errors"
	"fmt"
	"strconv"
	"strings"
)

func parsePesanan(baris string) (string, int, error) {
	// TODO: gunakan strings.Cut, strings.TrimSpace, strings.ToLower, strconv.Atoi
	return "", 0, errors.New("belum diimplementasikan")
}

func formatStruk(nama string, jumlah int) string {
	// TODO: "<jumlah>x <NAMA>" dengan strconv.Itoa dan strings.ToUpper
	_ = strconv.Itoa
	_ = strings.ToUpper
	return ""
}

func main() {
	nama, jumlah, err := parsePesanan(" Latte : 2 ")
	if err != nil {
		fmt.Println("error:", err)
		return
	}
	fmt.Println(formatStruk(nama, jumlah))
}

Output

Go runtime not loaded yet

Press Run to see the output, or Submit to check your code.

Ctrl/Cmd + Enter: Run · Ctrl/Cmd + Shift + Enter: Submit · Ctrl/Cmd + S: tidy the code (gofmt)