This tutorial talks about how to store characters and strings in Nim Language.

Nim Provides the following data types

  • Nim Character

  • String

  • NIm Character

Characters is an ascii digit represented by Char type in Nim and size is 1 byte in length.

It represents single characters such as digits, letters, symbols, and special characters, and throws an error if it contains multiple characters These are enclosed in single tick mark (`)

Example character variable

let
    char1=`a`
    char2=`b`

Invalid Character declaration and throws an error

let
    char4=`23`
    char5=`22`

Char type does not represent UTF-8 characters. use the Rune type to represent Unicode characters. Rune is a declared Unicode module which needs to import

String in NIM

The string is a group of characters, that contains words or statements or escape characters declared using double quotes

  • String literals with escape character
  • Raw String literals
  • Long String literals

Example of String literals

let
    str="abc"
    str1="2"

Multi-line strings are declared using the \n character

let
    str="abc\n def"

Another, Raw String literals, which does not escape characters prints the string without escape characters. Raw strings start with r character and enclose strings in double quotes.

echo r"Skip escape characters such as \n and \t"

Output:

Skip escape characters such as \n and \t

Long string literals:

Sometimes, We want to add long line strings, enclosed in triple quotes (""").

Long string literals are spanned across multiple lines and \ is not an escape character

Example:

echo “““First line. Second line third line four line \n \t \r”””

String Formatting example

strutils module provides a formatting feature

String concatenation example

Sometimes, adding one string to another string.

The & operator is used to append a string.

let str = "one" & " two"
echo str # one two

How to check whether strings are equal or not

There are two operators to check whether strings are equal or not

  • ==: check if two strings are equal and return true.
  • !==: check if two strings are not equal and return true.
echo "one" == "two"
echo "one" != "two"