String Fields and Functions
Strings have multiple built-in functions you can use.
let length: Int
Returns the number of characters in the string as an integer.
let example = "hello"
// Find the number of elements of the string.
let length = example.length
// `length` is `5`
-
fun concat(_ other: String): String
Concatenates the string other
to the end of the original string, but does not modify the original string. This function creates a new string whose length is the sum of the lengths of the string the function is called on and the string given as a parameter.
let example = "hello"
let new = "world"
// Concatenate the new string onto the example string and return the new string.
let helloWorld = example.concat(new)
// `helloWorld` is now `"helloworld"`
-
fun slice(from: Int, upTo: Int): String
Returns a string slice of the characters in the given string from start index from
up to, but not including, the end index upTo
. This function creates a new string whose length is upTo - from
. It does not modify the original string. If either of the parameters are out of the bounds of the string, the function will fail.
let example = "helloworld"
// Create a new slice of part of the original string.
let slice = example.slice(from: 3, upTo: 6)
// `slice` is now `"lowo"`
// Run-time error: Out of bounds index, the program aborts.
let outOfBounds = example.slice(from: 2, upTo: 10)
-
fun decodeHex(): [UInt8]
Returns an array containing the bytes represented by the given hexadecimal string.
The given string must only contain hexadecimal characters and must have an even length. If the string is malformed, the program aborts
let example = "436164656e636521"
example.decodeHex() // is `[67, 97, 100, 101, 110, 99, 101, 33]`
Last updated
Was this helpful?