Strings and Characters
8.1 String Basics
string is a mutable, value-semantic sequence of bytes (UTF-8 by convention).
var s = "Hello"
s.add(", World")
s &= "!"
echo s.len, " ", s[0], " ", s[^1] # length, first char, last char
echo s[0..4], " ", s[7..^1] # slicing
s[0] = 'J'
echo s.find("World"), " ", "World" in s8.2 std/strutils
import std/strutils
echo " hi ".strip, "abc".toUpperAscii, "a,b,c".split(','), @["a", "b"].join("-")
echo "hello".startsWith("he"), "hello".endsWith("lo"), "hello".contains("ll")
echo "abc".repeat(3), "x".align(5), "x".alignLeft(5, '.')
echo "42".parseInt + 1, "3.14".parseFloat, "true".parseBool
echo "Hello".replace("l", "L"), "a-b".multiReplace(("a", "x"), ("b", "y"))
echo "hello world".capitalizeAscii, "x".isAlphaAscii, "5".isDigit
echo "%1 is %2" % ["Nim", "fun"] # formatting with %
echo 255.toHex, 3.14159.formatFloat(ffDecimal, 2), 42.intToStr(5)8.3 String Formatting (std/strformat)
import std/strformat
let name = "Nim"; let ver = 2.2
echo fmt"{name} version {ver:.1f}"
echo &"{name:>10}|{42:05}|{255:x}|{3.14159:8.3f}"
echo fmt"{name=}" # debug: name=Nim8.4 Characters and Unicode
import std/unicode
let u = "héllo 🌍"
echo u.len # bytes
echo u.runeLen # code points
for r in u.runes: echo r
echo u.toUpper # Unicode-aware
echo ord('A'), chr(66)8.5 String Building and Performance
Use add and newStringOfCap(n) for efficient building. Avoid repeated & in loops.
std/strbasics for in-place operations. cstring for C interop (s.cstring).
8.6 Regular Expressions
std/re (PCRE wrapper, needs the PCRE library), std/nre, or the pure-Nim regex package (recommended):
import regex
var m: RegexMatch2
if "2025-10-24".match(re2"(\d{4})-(\d{2})-(\d{2})", m):
echo m.group(0)