Skip to main content

02 - Strings

In Motoko strings (type name is Text) can be written as text surrounded by double quotes.

"Hello, Motoko!"

Under the hood strings are UTF-8 encoded binaries and can contain any valid unicode.

import Debug "mo:base/Debug";
Debug.print("๐Ÿ‘ฉโ€๐Ÿ’ป ใ“ใ‚“ใซใกใฏ Motoko ๐Ÿ’ซ");


The concatenation operator # can be used to join strings together.

let x = "Joe";
"Hello, " # x # "!"
// "Hello, Joe!"

Escape Sequencesโ€‹

Motoko supports common string escape sequences. Here's all of them:

\rCarriage Return
\"Double Quote

For example to include a double quote (") character in a string literal it must be escaped by placing a backslash (\) character before it.

Here are a few examples of using escape sequences:

import Debug "mo:base/Debug";
Debug.print("Here is a double quote -> \" <-");

Similarly all backslash characters must be escaped:

import Debug "mo:base/Debug";
// A Windows filepath C:\Users\Motoko

// A Decorative border /\/\/\/\

Common methodsโ€‹

Strings are represented by the class Text that has a few useful methods.

You can get the size of the string by calling method size():

let myString : Text = "Hello, Motoko!";

Text.chars() returns an iterator that you can use to loop over the string's characters:

import Debug "mo:base/Debug";
import Char "mo:base/Char";

let myString : Text = "Hello, Motoko!";
for (char in myString.chars()) {

String could be compared to each other using == operator:

import Debug "mo:base/Debug";

let A = "A";
let B = "B";
let X = "A";

if (A == B) {
Debug.print("A and B are the same!")
} else {
Debug.print("A and B are different!")

if (A == X) {
Debug.print("A and X are the same!")
} else {
Debug.print("A and X are different!")

Converting other types to Textโ€‹

Most of the types can be converted to Text using toText() function from the type's module.

import Nat "mo:base/Nat";
let natVal : Nat = 32;
import Int "mo:base/Int";
let intVal : Int = -32;