Nim Programming Cookbook // Strings

String

Strip leading and trailing whitespace from a string

Problem

You want to remove unwated characters, such as whitespace, newline etc., from the beginning or end of a string.

Solution

import strutils
let aString = "    May had a little lamb    "
echo "Original string (", aString, ")"

let strBoth = strip(aString)
echo "Whitespace stripped at both ends (", strBoth, ")"

The default strip procedure will remove whitespaces both both ends. However, you can strip characters from only one end by using trailing=false and leading=false parameters.

let str2 = strip(aString, leading=false)
echo "Trailing whitespace stripped: (", str2, ")"

let str3 = strip(aString, trailing=false)
echo "Leading whitespace stripped: (", str3, ")"

You can specify more than one character to strip from the string (default: whitespace) by passing in a set of characers.

let str4 = "(* a comment (*-*) string in OCaml *)"
echo str4
echo strip(str4, chars={'(', '*', ')'})

Note the (* and *) stripped from the ends and not from the middle of the string.

Interpolating variables in Strings

Problem

Create a string in which variable values can be embedded.

Solution

import tables
import strutils

let characters = {"Bojack": "Horse", "Princess": "Cat", "Todd": "Human"}.toTable
for name, animal in characters:
    echo "$1 is a $2" % [name, animal]

Check the case of a string

Problem

Check if a string is an uppercase or a lowercase.

Solution

import strutils

var
  str1 = "lower"
  str2 = "UPPER"
  str3 = "MiXeD"

echo str1.isLowerAscii()
echo str3.isLowerAscii()

echo str2.isUpperAscii()
echo str3.isUpperAscii()

Change the case of a string

Problem

You need to change the case of a string to upper, lower, or to a sentence case (only first letter is upper).

Solution

import strutils

var
  str1 = "lower"
  str2 = "UPPER"
  str3 = "MiXeD"

echo str1.toUpperAscii()
echo str3.toUpperAscii()

echo str2.toLowerAscii()
echo str3.toLowerAscii()

echo str1.capitalizeAscii()
echo str3.capitalizeAscii()
echo str3.toLowerAscii().capitalizeAscii()