← Cookbook Strings and text Beginner · Pooka 0.5.0

Split, trim and join

Untidy text comes in, tidy text goes out: split it, trim it, drop the empty bits, and join it back together.

You will use

  • pooka/string: split, trim, is_empty, uppercase, slice, drop_start, join
  • string.split_once for key = value lines
  • string.pad_start for fixed-width numbers

The whole program

src/main.pooka
module main

import pooka/io
import pooka/list
import pooka/string

capitalise(word: String) -> String {
  string.uppercase(string.slice(word, 0, 1)) + string.drop_start(word, 1)
}

main() {
  let guests = "owl, fox ,  hare,,badger "
  |> string.split(",")
  |> list.map(string.trim)
  |> list.filter(fn(name: String) { !string.is_empty(name) })
  |> list.map(capitalise)
  io.println(string.join(guests, " · "))

  let line = match string.split_once("lamp = lit", "=") {
    Some(#(key, value)) -> string.trim(key) + " is " + string.trim(value)
    None -> "no setting here"
  }
  io.println(line)
  io.println(string.pad_start("7", 3, "0") + " guests")
  Nil
}

Run it

$ pooka run
Owl · Fox · Hare · Badger
lamp is lit
007 guests

How it works

  1. Split, then clean. "owl, fox , hare,,badger " splits on commas into pieces with spaces and one empty string. list.map(string.trim) tidies each piece, and the filter drops the empty one.
  2. Capitalise by hand. Take the first character with string.slice(word, 0, 1), upper-case it, and add back the rest with string.drop_start(word, 1).
  3. Split once for settings. string.split_once returns Some(#(before, after)) at the first =, or None if there is none, so values may contain more = signs safely.
  4. Pad for tables. string.pad_start("7", 3, "0") gives "007". pad_end pads on the right, which lines up text columns.

Try next: Pooka strings are UTF-8. string.length counts characters, string.byte_size counts bytes, and string.graphemes keeps emoji and accents in one piece.