Learn/Nim/8. Strings and a small project
Lesson 8 of 8
Sign in

Nim, lesson 8

Strings and a small project

Text is everywhere: names, commands, messages. A Nim string is a sequence of bytes that you can index, slice and grow, and the strutils module adds dozens of helpers on top.

Strings are sequences of characters

Indexing gives you a char, written with single quotes: 'H'. Strings are mutable when declared with var, so s[0] = 'J' would change the first letter.

Everyday helpers from strutils

The Ascii in toUpperAscii is a reminder that it only changes the letters A to Z. Strings in Nim are UTF-8 bytes, so for text with accents you would reach for the module instead.

2 exercises to try what you just read.

Exercise 1

Shout, flip and count

Press Ctrl Enter or Check to test your code.

Exercise 2

Receipt printer

Press Ctrl Enter or Check to test your code.

unicode

Character sets

Nim has a built-in set type that is great for character tests. {'a', 'e', 'i', 'o', 'u'} is a set of chars, and in checks membership:

strutils also has ready-made sets, such as Digits and Letters.

Lining text up

align pads on the left and alignLeft pads on the right, which is how you build neat columns: "42".align(5) is " 42". With strformat, fmt"{name:<8}{price:>5}" does the same inside a template.

Putting it all together

The final exercise uses every lesson so far: reading input, parsing numbers, a procedure, a seq of tuples, a loop that totals things up, a decision for an empty receipt, and formatted output. A tuple with named fields is an easy way to bundle one item:

A good plan: read N; parse each line into an Item with a small proc; print each line while adding to the totals; track the most expensive line with a strict > comparison so the first one wins a tie.

Further reading

  • The strutils module
  • Nim Tutorial (Part I): characters, strings and sets
  • Nim Tutorial (Part I): tuples

Read one line of text and print three lines:

  1. the text in uppercase,
  2. the text reversed,
  3. Vowels: N, where N counts the letters a e i o u in either case.

Input: one line (letters, spaces and punctuation; it may be empty).

prints

Build the reversed text by looping over the indexes from the last one down to 0.

Print a receipt for a shopping trip.

Input: the first line is the number of items N (0 or more). Each of the next N lines has an item name (one word), a quantity and a unit price in whole euros, separated by spaces.

Output:

  • one line per item, in input order: name xQTY = LINE_TOTAL,
  • then Items: and the sum of all quantities,
  • then Total: and the sum of all line totals,
  • then Biggest: and the name of the item with the largest line total (the first one if there is a tie), or none if there are no items.

prints

var s = "Hello, Nim"
echo s.len        # 10
echo s[0]         # H  (a char)
echo s[^1]        # m  (the last char)
echo s[0..4]      # Hello  (a slice is a new string)
s.add("!")        # s is a var, so it can grow
echo s & " Bye"   # Hello, Nim! Bye
import std/strutils

let t = "Hello, Nim"
echo t.toUpperAscii             # HELLO, NIM
echo t.toLowerAscii             # hello, nim
echo t.contains("Nim")          # true
echo t.startsWith("He")         # true
echo t.replace("l", "L")        # HeLLo, Nim
echo "a,b,c".split(',')         # @["a", "b", "c"]
echo @["x", "y"].join("-")      # x-y
echo "ab".repeat(3)             # ababab
let ch = 'e'
if ch in {'a', 'e', 'i', 'o', 'u'}:
  echo "vowel"
type Item = tuple[name: string, qty: int, price: int]

let apples: Item = (name: "apple", qty: 3, price: 2)
echo apples.name, " costs ", apples.qty * apples.price
Hello there
HELLO THERE
ereht olleH
Vowels: 4
3
apple 3 2
bread 1 4
cheese 2 5
apple x3 = 6
bread x1 = 4
cheese x2 = 10
Items: 6
Total: 20
Biggest: cheese