Version: Next

Strings & Bytes

Strings#

Strings are defined using the built-in string type like this:

let a: string = "Hello Alice";

or with single quotes:

let a_: string = 'Hello Alice';

Concatenating Strings#

Strings can be concatenated using the + operator.

let name: string = "Alice";
let greeting: string = "Hello";
let full_greeting: string = greeting + " " + name;

Extracting Substrings#

Substrings can be extracted using the predefined function String.sub. The first character has index 0 and the interval of indices for the substring has inclusive bounds.

let name: string = "Alice";
let slice: string = String.sub (0 as nat, 1 as nat, name);

⚠️ Notice that the offset and length of the slice are natural numbers.

Length of Strings#

The length of a string can be found using a built-in function:

let name: string = "Alice";
let length: nat = String.length(name); // length == 5

Bytes#

Byte literals are defined using the prefix 0x followed by hexadecimal digits like this:

let b : bytes = 0x7070;

Concatenating Bytes#

Bytes can be concatenated using the Bytes.concat function.

let white: bytes = 0xffff;
let black: bytes = 0x0000;
let mixed: bytes = Bytes.concat(white, black); // 0xffff0000

Extracting Bytes#

Bytes can be extracted using the predefined function Bytes.sub. The first parameter takes the start index and the second parameter takes the number of bytes. Pay special attention to how bytes are indexed.

let b : bytes = 0x12345678;
let slice : bytes = Bytes.sub (1 as nat, 2 as nat, b); // 0x3456

Length of Bytes#

The length of bytes can be found using a built-in function Bytes.length:

let b : bytes = 0x123456;
let length : nat = Bytes.length(b); // length = 3