Skip to content
Tutorials Center
My learning

Topics

Lesson 18 of 36 · Collections and Strings

Strings, strutils, strformat and Runes

Work with Nim strings: bytes versus characters, slicing, concatenation, strutils helpers, split and join, strformat formatting, multi-line strings and Unicode with std/unicode.

Text handling decides whether a language feels pleasant. Nim's string is a mutable sequence of bytes, conventionally holding UTF-8 text. It is a value type (assignment copies), it grows with add, and it comes with a large toolbox in std/strutils, formatted output in std/strformat, and proper Unicode support in std/unicode. The one thing to understand early is the difference between bytes, characters (the char type) and runes (Unicode characters).

Nim code here is read-only (no compiler on this site). The C stand-ins are runnable and show the byte-versus-character difference.

Basics

NIM
var greeting = "Hello"
greeting.add ", Nim"             # append in place
let full = greeting & "!"        # & makes a new string
echo full                        # Hello, Nim!
echo full.len                    # 11  (bytes)
echo full[0]                     # 'H'  (a char)
echo full[^1]                    # '!'
echo full[0 .. 4]                # Hello
echo full == "Hello, Nim!"       # true

Strings are zero-based, support slices and ^ indexes like sequences, and compare with ==, < and cmp. Special literals:

NIM
let path = r"C:\temp\notes.txt"          # raw string: no escapes processed
let poem = """Roses are red,
violets are blue"""                      # multi-line string
let tab = "a\tb"                         # escapes like \t \n \\ \"

strutils: the everyday helpers

NIM
import std/strutils

let s = "  The Quick Brown Fox  "
echo s.strip()                            # The Quick Brown Fox
echo s.toLowerAscii()                     #   the quick brown fox
echo s.strip().split(' ')                 # @["The", "Quick", "Brown", "Fox"]
echo @["a", "b", "c"].join("-")           # a-b-c
echo "banana".replace("an", "AN")         # bANANa
echo "banana".count("an")                 # 2
echo "banana".find("nan")                 # 2  (-1 if absent)
echo "Hello".startsWith("He")             # true
echo "Hello".endsWith("lo")               # true
echo "ab".repeat(3)                       # ababab
echo "7".parseInt() + 1                   # 8
echo "nim" in "I love nim"                # true
echo "42".align(6)                        #     42   (right-aligned in 6)
echo "x".alignLeft(4) & "|"               # x   |
echo "title case".capitalizeAscii()       # Title case

The split procedure with no argument splits on whitespace; splitLines splits at line ends; splitWhitespace is explicit. Functions with Ascii in the name affect only ASCII letters, which is fast and fine for English text.

Formatting with strformat

NIM
import std/strformat

let name = "Ada"
let score = 93.456
echo fmt"Hello, {name}! Score: {score:.1f}"     # Hello, Ada! Score: 93.5
echo fmt"{42:5}|{42:<5}|{42:05}"                #    42|42   |00042
echo fmt"{255:x} {255:b} {255:#X}"              # ff 11111111 0xFF
echo fmt"{name=} {1 + 2=}"                      # name=Ada 1 + 2=3

fmt"..." evaluates any expression inside braces at the point where it appears. After a colon you give a format spec (width, alignment, precision, base). To write a literal brace, double it: {{ and }}. The &"..." form is similar but supports normal escape sequences.

Bytes, characters and runes

A char is one byte. Text that is not plain ASCII needs more than one byte per visible character in UTF-8:

Visible character Bytes in UTF-8
A 1
é 2
€ 3
😀 4

So "héllo".len is 6, not 5, and "héllo"[1] is half of the letter é. When you need characters rather than bytes, use std/unicode, where a Rune is a full Unicode code point:

NIM
import std/unicode

let word = "héllo wörld"
echo word.len                  # 13 bytes
echo word.runeLen              # 11 characters

for r in word.runes:
  stdout.write r, " "          # h é l l o   w ö r l d

echo word.toUpper()            # HÉLLO WÖRLD   (Unicode-aware)
echo word.reversed()           # dlröw olléh

runes iterates characters, toRunes returns a seq[Rune], and runeAt, runeLen, toUpper, toLower, reversed are all UTF-8 aware. Keep strutils procedures for protocol and ASCII work, and reach for unicode for user-facing text.

flowchart LR
  S["string<br/>bytes in UTF-8"] -- "s[i]" --> C["char<br/>one byte"]
  S -- "s.runes" --> R["Rune<br/>one Unicode character"]
  S -- "s.len" --> B["byte count"]
  S -- "s.runeLen" --> N["character count"]

Caption: the same text, viewed as bytes or as characters.

String building and performance

Repeated s = s & x allocates each time. For many appends, use add, which grows the same buffer; for numbers and values use fmt or $:

NIM
var buf = ""
for i in 1 .. 5:
  buf.add $i
  buf.add ' '
echo buf.strip()               # 1 2 3 4 5

There is also std/strutils.join for assembling lists, and std/strformat for templates.

Stand-in: bytes versus characters

This C stand-in decodes UTF-8 by hand, counting characters as bytes that are not continuation bytes (those starting with bits 10). It prints the same two numbers as len and runeLen.

C Stand-in: len versus runeLen

Press Run (or Ctrl + Enter) to see the result here.

Program input · what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

The first word has 5 bytes and 5 characters. The accented text has more bytes than characters, and the euro sign alone takes 3 bytes.

Stand-in: split and join

C Stand-in: split on a separator

Press Run (or Ctrl + Enter) to see the result here.

Program input · what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

In Nim split and join return and accept real sequences of strings, so there is no manual buffer handling.

Check your understanding

Quick check · 4 questions

of 4 answered You scored / 4 · perfect!

  1. 1. What does "héllo".len return in Nim?

    len counts bytes; é takes 2 bytes in UTF-8, so the length is 6. runeLen gives 5.
  2. 2. Which module gives you Unicode-aware character iteration?

    std/unicode provides Rune, runes, runeLen, toUpper and more.
  3. 3. Which line prints Hello, Ada! if name = "Ada"?

    fmt from std/strformat interpolates expressions in braces.
  4. 4. What is the best way to append to a string many times in a loop?

    add extends the same buffer; repeated & allocates new strings.

Summary

  • A Nim string is a mutable byte sequence (UTF-8 by convention); it supports indexing, slices, & and add.
  • std/strutils has strip, split, join, replace, find, startsWith, parseInt and more.
  • fmt"..." from std/strformat formats values inline with width, precision and base specs.
  • len counts bytes; use std/unicode (Rune, runes, runeLen) when you need characters.

Next: Objects and Tuples in Nim