String Methods
Methods available on String types.
Inspection
count
Returns the total number of characters in the string.
fn count(): Intlet greeting = "hello";
print(greeting.count()); // 5indexOf
Returns the index of the first occurrence of sub, or Null if not found.
fn indexOf(sub: String): Int|Nulllet sentence = "hello world";
print(sentence.indexOf(sub: "world")); // 6
print(sentence.indexOf(sub: "mars")); // nullcontains
Checks if the string contains the specified substring.
fn contains(sub: String): Boollet sentence = "hello world";
if sentence.contains(sub: "hello") {
print("Found!");
}startsWith
Checks if the string begins with the specified substring.
fn startsWith(sub: String): Boollet filename = "document.txt";
print(filename.startsWith(sub: "doc")); // trueendsWith
Checks if the string ends with the specified substring.
fn endsWith(sub: String): Boollet imageName = "picture.png";
print(imageName.endsWith(sub: ".png")); // trueTransformation
lower
Converts the string to lowercase.
fn lower(): Stringlet shout = "HELLO";
print(shout.lower()); // "hello"upper
Converts the string to uppercase.
fn upper(): Stringlet greeting = "hello";
print(greeting.upper()); // "HELLO"trim
Removes whitespace from both the beginning and end of the string.
fn trim(): Stringlet userInput = " hello ";
print(userInput.trim()); // "hello"trimLeft / ltrim
Removes whitespace from the beginning of the string.
fn trimLeft(): Stringlet s = " hello";
print(s.trimLeft()); // "hello"trimRight / rtrim
Removes whitespace from the end of the string.
fn trimRight(): Stringlet s = "hello ";
print(s.trimRight()); // "hello"replace
Replaces all occurrences of the old string with the new string.
fn replace(old: String, new: String): Stringlet template = "hello world";
print(template.replace(old: "world", new: "universe")); // "hello universe"split
Splits the string into an array of substrings using the delimiter sep.
fn split(sep: String): Array<String>let csvData = "apple,banana,cherry";
let items = csvData.split(sep: ",");
// items is ["apple", "banana", "cherry"]substring
Extracts a portion of the string. If len is omitted, extracts to the end.
fn substring(start: Int, len: Int?): Stringlet phrase = "hello world";
print(phrase.substring(start: 0, len: 5)); // "hello"
print(phrase.substring(start: 6)); // "world"reverse
Reverses the characters in the string.
fn reverse(): Stringlet word = "abc";
print(word.reverse()); // "cba"repeat
Repeats the string n times.
fn repeat(n: Int): Stringlet star = "*";
print(star.repeat(n: 5)); // "*****"pad
Pads the string to a certain length with another string.
fn pad(length: Int, padString: String = " ", type: Int = STR_PAD_RIGHT): Stringlet s = "Hello";
print(s.pad(length: 10, padString: ".")); // "Hello....."