Strings
string is the native UTF-8 text type in tyrus. Source syntax is concise and statically checked, while the runtime implementation is native.
Quoted Strings
const greeting: string = "hello";
const alternative: string = 'hello';The formatter normalizes quotes according to quote_style, unless it is set to "off", which preserves the original quotes and escapes of every string literal.
Multiline Strings
A string delimited by """ can span multiple lines while staying aligned with the surrounding code. The compiler dedents it at compile time: from every line, it strips as many leading spaces as the closing """ itself is indented with, and it drops a first line left blank right after the opening """. The result is an ordinary string literal, so there is no runtime cost to writing an aligned query or template instead of one flush against the left margin.
const query: string = """
SELECT id, name
FROM users
WHERE active = true
""";The dedent margin only counts spaces; a """ closed on a tab-indented line measures a margin of zero, so use spaces for the indentation you want stripped.
Template Literals
Use template literals for interpolation and multiline text.
const name: string = "Ada";
const greeting: string = `Hello, ${name}`; // Hello, Ada
const message: string = `line one
line two`;
const pi: f64 = 3.141592;
const id: i32 = 42;
const status: string = `Value: ${pi:.2f} | Code: ${id:04d}`; // Value: 3.14 | Code: 0042An interpolation may carry a format specifier after :, .Nf fixes a float to exactly N decimal places, and 0Nd zero-pads an integer to a total width of N characters. .Nf requires a float value and 0Nd requires an integer value; a mismatch is a compile error (E0717) naming the required kind.
A union-typed value may be interpolated too. Which variant it holds is a run-time fact, so the rendering is chosen at run time and matches what print would print for that variant.
Literal String Types
String literals can participate in literal unions and tagged unions.
A literal union is an ordinary value: compare it with any of its variants (status === "active"), branch on it with a match that needs no _ when it covers every variant, build one with a ternary, collect them in an array, and call on it anything a string accepts, every variant of a string-literal union is a string. The comparison is a single byte check rather than a text comparison, because such a union is represented by which variant it holds and nothing else.
type Role = "admin" | "operator" | "viewer";
interface Success {
tag: "success";
data: string;
}Literal values are not enum members
Use literal strings for small closed text domains. Use enum when the domain needs named members and native enum semantics.
Grapheme clusters
chars() gives Unicode scalar values; graphemes() gives what a reader calls characters. They differ wherever one visible character is written with several scalar values, an emoji built from a zero-width joiner sequence, or a letter followed by a combining accent.
const astronaut: string = "👨🚀";
print(astronaut.chars().length); // 3
print(astronaut.graphemes().length); // 1Indexing, slicing and length count scalar values, not clusters: that is the unit every position in the string API is measured in, and it is what makes text.charAt(text.length - 1) the last one. graphemes() is the answer to the display question, how many characters a reader sees, and where a cursor would stop, and it returns string[], because a cluster can hold more than one scalar value.
String Properties
length
const message: string = "tyrus";
const count: usize = message.length; // 5
const accented: string = "héllo";
const characters: usize = accented.length; // 5 characters, not 6 bytes
const launch: string = "a🚀b";
const positions: usize = launch.length; // 3, one position per characterlength is read from the value, not counted: a string carries its character count alongside its text, so asking for it costs the same whether the string holds three characters or three million. U+0000 is an ordinary character in a string, the text is delimited by its recorded length, not by a terminator, so "a\u{0}b".length is 3 and the whole of it survives comparison, interpolation and printing.
length counts characters, Unicode scalar values, never the underlying UTF-8 bytes, so it agrees with chars() on any text. Every position in the string API is measured in that same unit: charAt(), charCodeAt(), slice(), substring(), indexOf(), lastIndexOf(), padStart() and padEnd() all count characters, which is what makes text.charAt(text.length - 1) the last character of any string, accented or not.
Methods
| Category | Methods |
|---|---|
| Case conversion | toUpperCase(), toLowerCase() |
| Case transformation | toSlugCase(), toDashCase(), toKebabCase(), toPascalCase(), toCamelCase(), toSnakeCase() |
| Trimming | trim(), trimStart(), trimEnd() |
| Searching | includes(), startsWith(), endsWith(), indexOf(), lastIndexOf(), search() |
| Slicing & extracting | slice(), substring(), charAt(), charCodeAt(), truncate(), truncateEllipsis() |
| Transforming | replace(), repeat(), padStart(), padEnd(), concat(), split() |
| HTML & encoding | stripHtml(), escapeHtml(), urlEncode(), urlDecode() |
| Pattern matching | match(), matchAll() |
| Iteration | chars(), graphemes() |
Case conversion
toUpperCase()
Returns the string with all uppercase characters.
toUpperCase(): stringconst shout: string = "tyrus";
const loud: string = shout.toUpperCase(); // TYRUSerror
const flag: boolean = true;
const upper: string = flag.toUpperCase(); error[E0599]: no method named `toUpperCase` for type `boolean`
at /src/main.tyr:2:23
const upper: string = flag.toUpperCase();
^^^^^^^^^^^^^^^^^^
help: check the member name and the receiver type; hover the value to see its typetoLowerCase()
Returns the string with all lowercase characters.
toLowerCase(): stringconst shout: string = "TYRUS";
const quiet: string = shout.toLowerCase(); // "tyrus"error
const flag: boolean = true;
const lower: string = flag.toLowerCase(); error[E0599]: no method named `toLowerCase` for type `boolean`
at /src/main.tyr:2:23
const lower: string = flag.toLowerCase();
^^^^^^^^^^^^^^^^^^
help: check the member name and the receiver type; hover the value to see its typeCase transformation
toSlugCase()
Normalizes the string into a URL-friendly slug. Strips accents via NFKD decomposition, removes non-alphanumeric characters, and joins words with hyphens.
toSlugCase(): stringconst title: string = "Como criar uma API em Tyrus!";
const slug: string = title.toSlugCase(); // "como-criar-uma-api-em-tyrus"
const greeting: string = "Hällo Wörld";
const clean: string = greeting.toSlugCase(); // "hallo-world"error
const flag: boolean = true;
const slug: string = flag.toSlugCase(); error[E0599]: no method named `toSlugCase` for type `boolean`
at /src/main.tyr:2:22
const slug: string = flag.toSlugCase();
^^^^^^^^^^^^^^^^^
help: check the member name and the receiver type; hover the value to see its typetoDashCase()
Converts the string to dash-case (lowercase words joined by hyphens). Tokenizes on whitespace, underscores, hyphens and camelCase boundaries. Unlike toSlugCase(), accents are preserved.
toDashCase(): stringconst phrase: string = "hello world example";
const dashed: string = phrase.toDashCase(); // "hello-world-example"
const camel: string = "HelloWorldExample";
const result: string = camel.toDashCase(); // "hello-world-example"error
const flag: boolean = true;
const dashed: string = flag.toDashCase(); error[E0599]: no method named `toDashCase` for type `boolean`
at /src/main.tyr:2:24
const dashed: string = flag.toDashCase();
^^^^^^^^^^^^^^^^^
help: check the member name and the receiver type; hover the value to see its typetoKebabCase()
Alias for toDashCase().
toKebabCase(): stringconst phrase: string = "hello world example";
const kebab: string = phrase.toKebabCase(); // "hello-world-example"toKebabCase() is an alias for toDashCase().
toPascalCase()
Converts the string to PascalCase. Each word is capitalized and joined without separators.
toPascalCase(): stringconst phrase: string = "hello world example";
const pascal: string = phrase.toPascalCase(); // "HelloWorldExample"
const snake: string = "hello_world_example";
const result: string = snake.toPascalCase(); // "HelloWorldExample"error
const flag: boolean = true;
const pascal: string = flag.toPascalCase(); error[E0599]: no method named `toPascalCase` for type `boolean`
at /src/main.tyr:2:24
const pascal: string = flag.toPascalCase();
^^^^^^^^^^^^^^^^^^^
help: check the member name and the receiver type; hover the value to see its typetoCamelCase()
Converts the string to camelCase. The first word is lowercase, subsequent words are capitalized.
toCamelCase(): stringconst phrase: string = "hello world example";
const camel: string = phrase.toCamelCase(); // "helloWorldExample"
const pascal: string = "HelloWorldExample";
const result: string = pascal.toCamelCase(); // "helloWorldExample"error
const flag: boolean = true;
const camel: string = flag.toCamelCase(); error[E0599]: no method named `toCamelCase` for type `boolean`
at /src/main.tyr:2:23
const camel: string = flag.toCamelCase();
^^^^^^^^^^^^^^^^^^
help: check the member name and the receiver type; hover the value to see its typetoSnakeCase()
Converts the string to snake_case (lowercase words joined by underscores).
toSnakeCase(): stringconst phrase: string = "hello world example";
const snake: string = phrase.toSnakeCase(); // "hello_world_example"
const camel: string = "HelloWorldExample";
const result: string = camel.toSnakeCase(); // "hello_world_example"error
const flag: boolean = true;
const snake: string = flag.toSnakeCase(); error[E0599]: no method named `toSnakeCase` for type `boolean`
at /src/main.tyr:2:23
const snake: string = flag.toSnakeCase();
^^^^^^^^^^^^^^^^^^
help: check the member name and the receiver type; hover the value to see its typeTrimming
trim()
Removes whitespace from both ends of the string.
trim(): stringconst padded: string = " hello ";
const clean: string = padded.trim(); // "hello"error
const value: i32 = 42;
const clean: string = value.trim(); error[E0599]: no method named `trim` for type `i32`
at /src/main.tyr:2:23
const clean: string = value.trim();
^^^^^^^^^^^^
help: check the member name and the receiver type; hover the value to see its typetrimStart()
Removes whitespace from the start of the string.
trimStart(): stringconst padded: string = " hello ";
const left: string = padded.trimStart(); // "hello "error
const value: i32 = 42;
const left: string = value.trimStart(); error[E0599]: no method named `trimStart` for type `i32`
at /src/main.tyr:2:22
const left: string = value.trimStart();
^^^^^^^^^^^^^^^^^
help: check the member name and the receiver type; hover the value to see its typetrimEnd()
Removes whitespace from the end of the string.
trimEnd(): stringconst padded: string = " hello ";
const right: string = padded.trimEnd(); // " hello"error
const value: i32 = 42;
const right: string = value.trimEnd(); error[E0599]: no method named `trimEnd` for type `i32`
at /src/main.tyr:2:23
const right: string = value.trimEnd();
^^^^^^^^^^^^^^^
help: check the member name and the receiver type; hover the value to see its typeSearching
includes()
Checks if the string contains a substring.
includes(search: string): booleanconst sentence: string = "tyrus is native";
const found: boolean = sentence.includes("native"); // trueerror
const sentence: string = "tyrus is native";
const found: boolean = sentence.includes(42); error[E0308]: type mismatch for `includes`: expected `string`, found `integer literal`
at /src/main.tyr:2:24
const found: boolean = sentence.includes(42);
^^^^^^^^^^^^^^^^^^^^^
help: change the value or the annotation so their types match; convert numbers explicitly with `value as <type>`startsWith()
Checks if the string starts with a substring.
startsWith(search: string): booleanconst filename: string = "main.tyr";
const isSource: boolean = filename.startsWith("main."); // trueerror
const filename: string = "main.tyr";
const isSource: boolean = filename.startsWith(true); error[E0308]: type mismatch for `startsWith`: expected `string`, found `boolean`
at /src/main.tyr:2:27
const isSource: boolean = filename.startsWith(true);
^^^^^^^^^^^^^^^^^^^^^^^^^
help: change the value or the annotation so their types match; convert numbers explicitly with `value as <type>`endsWith()
Checks if the string ends with a substring.
endsWith(search: string): booleanconst filename: string = "main.tyr";
const isTyrus: boolean = filename.endsWith(".tyr"); // trueerror
const filename: string = "main.tyr";
const isTyrus: boolean = filename.endsWith(42); error[E0308]: type mismatch for `endsWith`: expected `string`, found `integer literal`
at /src/main.tyr:2:26
const isTyrus: boolean = filename.endsWith(42);
^^^^^^^^^^^^^^^^^^^^^
help: change the value or the annotation so their types match; convert numbers explicitly with `value as <type>`indexOf()
Returns the index of the first occurrence of a substring, or -1.
indexOf(search: string, start?: i64): i64const text: string = "hello world";
const position: i64 = text.indexOf("world"); // 6
const missing: i64 = text.indexOf("rust"); // -1error
const text: string = "hello world";
const position: i64 = text.indexOf(["hello"]); error[E0308]: type mismatch for `indexOf`: expected `string`, found `string[]`
at /src/main.tyr:2:23
const position: i64 = text.indexOf(["hello"]);
^^^^^^^^^^^^^^^^^^^^^^^
help: change the value or the annotation so their types match; convert numbers explicitly with `value as <type>`lastIndexOf()
Returns the index of the last occurrence of a substring, or -1.
lastIndexOf(search: string, start?: i64): i64const path: string = "src/main.tyr";
const lastSlash: i64 = path.lastIndexOf("/"); // 3error
const path: string = "src/main.tyr";
const lastSlash: i64 = path.lastIndexOf(42); error[E0308]: type mismatch for `lastIndexOf`: expected `string`, found `integer literal`
at /src/main.tyr:2:24
const lastSlash: i64 = path.lastIndexOf(42);
^^^^^^^^^^^^^^^^^^^^
help: change the value or the annotation so their types match; convert numbers explicitly with `value as <type>`search()
Searches for a pattern using a regular expression and returns the index of the match.
search(pattern: Regex): i64const main = (): void => {
const email: string = "[email protected]";
const atSign: i32 = email.search(/@/); // 4
print(atSign); // 4
};error
const main = (): void => {
const email: string = "[email protected]";
const atSign: i32 = email.search("@");
};error[E0308]: type mismatch for `search`: expected `Regex`, found `string`
at /src/main.tyr:3:25
const atSign: i32 = email.search("@"); // [!code error]
^^^^^^^^^^^^^^^^^
help: change the value or the annotation so their types match; convert numbers explicitly with `value as <type>`Slicing and extracting
slice()
Extracts a section of the string and returns it as a new string.
slice(start?: i64, end?: i64): stringconst code: string = "tyrus-lang";
const lang: string = code.slice(6); // "lang"
const sub: string = code.slice(0, 5); // "tyrus"error
const code: string = "tyrus-lang";
const result: string = code.slice("6"); error[E0308]: type mismatch for `slice`: expected `i64`, found `string`
at /src/main.tyr:2:24
const result: string = code.slice("6");
^^^^^^^^^^^^^^^
help: change the value or the annotation so their types match; convert numbers explicitly with `value as <type>`substring()
Returns a substring starting at a given index.
substring(start: i64, end?: i64): stringconst version: string = "v0.1.0";
const numeric: string = version.substring(1); // "0.1.0"error
const version: string = "v0.1.0";
const numeric: string = version.substring("1"); error[E0308]: type mismatch for `substring`: expected `i64`, found `string`
at /src/main.tyr:2:25
const numeric: string = version.substring("1");
^^^^^^^^^^^^^^^^^^^^^^
help: change the value or the annotation so their types match; convert numbers explicitly with `value as <type>`charAt()
Returns the character at a specified index.
charAt(index: i64): stringconst word: string = "tyrus";
const letter: string = word.charAt(0); // "t"error
const word: string = "tyrus";
const letter: string = word.charAt("0"); error[E0308]: type mismatch for `charAt`: expected `usize`, found `string`
at /src/main.tyr:2:24
const letter: string = word.charAt("0");
^^^^^^^^^^^^^^^^
help: change the value or the annotation so their types match; convert numbers explicitly with `value as <type>`charCodeAt()
Returns the Unicode code point of the character at a specified index.
charCodeAt(index: i64): u32const main = (): void => {
const letter: string = "A";
const code: i32 = letter.charCodeAt(0); // 65
print(code); // 65
};error
const main = (): void => {
const letter: string = "A";
const code: i32 = letter.charCodeAt("0");
};error[E0308]: type mismatch for `charCodeAt`: expected `usize`, found `string`
at /src/main.tyr:3:23
const code: i32 = letter.charCodeAt("0"); // [!code error]
^^^^^^^^^^^^^^^^^^^^^^
help: change the value or the annotation so their types match; convert numbers explicitly with `value as <type>`truncate()
Truncates the string to a maximum number of code points.
truncate(maxLength: i64): stringconst text: string = "Hello, World!";
const short: string = text.truncate(5); // "Hello"
const small: string = text.truncate(3); // "Hel"error
const text: string = "hello";
const bad: string = text.truncate("ten"); error[E0308]: type mismatch for `truncate`: expected `usize`, found `string`
at /src/main.tyr:2:21
const bad: string = text.truncate("ten");
^^^^^^^^^^^^^^^^^^^^
help: change the value or the annotation so their types match; convert numbers explicitly with `value as <type>`truncateEllipsis()
Truncates the string to a maximum number of code points and appends ... when the text overflows.
truncateEllipsis(maxLength: i64): stringconst text: string = "Hello, World!";
const short: string = text.truncateEllipsis(8); // "Hello..."
const fits: string = "hello".truncateEllipsis(10); // "hello"error
const text: string = "hello";
const bad: string = text.truncateEllipsis("ten"); error[E0308]: type mismatch for `truncateEllipsis`: expected `usize`, found `string`
at /src/main.tyr:2:21
const bad: string = text.truncateEllipsis("ten");
^^^^^^^^^^^^^^^^^^^^^^^^^^^^
help: change the value or the annotation so their types match; convert numbers explicitly with `value as <type>`Transforming
replace()
Replaces a substring or pattern with a replacement string.
replace(search: string | Regex, replacement: string): stringconst path: string = "src/main.ts";
const updated: string = path.replace(".ts", ".tyr"); // "src/main.tyr"error
const path: string = "src/main.ts";
const updated: string = path.replace(".ts", 42); error[E0308]: type mismatch for `replace`: expected `string`, found `integer literal`
at /src/main.tyr:2:25
const updated: string = path.replace(".ts", 42);
^^^^^^^^^^^^^^^^^^^^^^^
help: change the value or the annotation so their types match; convert numbers explicitly with `value as <type>`repeat()
Returns a new string with the original repeated a given number of times.
repeat(count: i64): stringconst divider: string = "-".repeat(20); // "--------------------"
const pattern: string = "ab".repeat(3); // "ababab"error
const divider: string = "-".repeat("20"); error[E0308]: type mismatch for `repeat`: expected `usize`, found `string`
at /src/main.tyr:1:25
const divider: string = "-".repeat("20");
^^^^^^^^^^^^^^^^
help: change the value or the annotation so their types match; convert numbers explicitly with `value as <type>`padStart()
Pads the start of the string with a filler string to reach a target length.
padStart(targetLength: i64, fill?: string): stringconst id: string = "42";
const padded: string = id.padStart(5, "0"); // "00042"error
const id: string = "42";
const padded: string = id.padStart("5"); error[E0308]: type mismatch for `padStart`: expected `usize`, found `string`
at /src/main.tyr:2:24
const padded: string = id.padStart("5");
^^^^^^^^^^^^^^^^
help: change the value or the annotation so their types match; convert numbers explicitly with `value as <type>`padEnd()
Pads the end of the string with a filler string to reach a target length.
padEnd(targetLength: i64, fill?: string): stringconst label: string = "Name";
const padded: string = label.padEnd(20, "."); // "Name................"error
const label: string = "Name";
const padded: string = label.padEnd("20"); error[E0308]: type mismatch for `padEnd`: expected `usize`, found `string`
at /src/main.tyr:2:24
const padded: string = label.padEnd("20");
^^^^^^^^^^^^^^^^^^
help: change the value or the annotation so their types match; convert numbers explicitly with `value as <type>`concat()
Concatenates the string with one or more strings.
Keeping a string beyond the value it was read from, pushing it into an array, capturing it in a closure, storing it in a field, no longer copies the text. The two share one buffer and each holds a reference to it, which is sound precisely because a string is immutable: two readers of one buffer can never disagree.
A chain of + costs one allocation, not one per operator: a + b + c + d measures every operand first, each string carries its own length, so measuring reads nothing, and then fills a single buffer.
concat(...strings: string[]): stringconst first: string = "Hello";
const second: string = " World";
const combined: string = first.concat(second); // "Hello World"error
const first: string = "Hello";
const combined: string = first.concat(42); error[E0308]: type mismatch for `concat`: expected `string`, found `integer literal`
at /src/main.tyr:2:26
const combined: string = first.concat(42);
^^^^^^^^^^^^^^^^
help: change the value or the annotation so their types match; convert numbers explicitly with `value as <type>`split()
Splits the string into an array of substrings using a separator.
split(separator: string | Regex): string[]const csv: string = "rust,go,tyrus";
const languages: string[] = csv.split(",");
// ["rust", "go", "tyrus"]
const sentence: string = "hello world";
const words: string[] = sentence.split(" ");
// ["hello", "world"]error
const csv: string = "rust,go,tyrus";
const languages: string[] = csv.split(42); error[E0308]: type mismatch for `split`: expected `string`, found `integer literal`
at /src/main.tyr:2:29
const languages: string[] = csv.split(42);
^^^^^^^^^^^^^
help: change the value or the annotation so their types match; convert numbers explicitly with `value as <type>`HTML and encoding
stripHtml()
Removes all HTML tags from the string, leaving only the text content. Decodes common HTML entities (<, >, &, ", ').
stripHtml(): stringconst html: string = "<p>Hello <b>World</b></p>";
const text: string = html.stripHtml(); // Hello World
const link: string = "<a href=\"url\">click here</a>";
const plain: string = link.stripHtml(); // click hereerror
const flag: boolean = true;
const text: string = flag.stripHtml(); error[E0599]: no method named `stripHtml` for type `boolean`
at /src/main.tyr:2:22
const text: string = flag.stripHtml();
^^^^^^^^^^^^^^^^
help: check the member name and the receiver type; hover the value to see its typeescapeHtml()
Escapes special characters into HTML entities (& < > " '), preventing XSS injection.
escapeHtml(): stringconst code: string = "<script>alert('hack')</script>";
const safe: string = code.escapeHtml(); // "<script>alert('hack')</script>"error
const flag: boolean = true;
const safe: string = flag.escapeHtml(); error[E0599]: no method named `escapeHtml` for type `boolean`
at /src/main.tyr:2:22
const safe: string = flag.escapeHtml();
^^^^^^^^^^^^^^^^^
help: check the member name and the receiver type; hover the value to see its typeurlEncode()
Percent-encodes the string for use as a URL query parameter. Encodes all characters except unreserved characters (letters, digits, -, _, ., ~).
urlEncode(): stringconst query: string = "hello world & friends";
const encoded: string = query.urlEncode(); // "hello%20world%20%26%20friends"
const path: string = "a/b?c=d";
const safe: string = path.urlEncode(); // "a%2Fb%3Fc%3Dd"error
const flag: boolean = true;
const encoded: string = flag.urlEncode(); error[E0599]: no method named `urlEncode` for type `boolean`
at /src/main.tyr:2:25
const encoded: string = flag.urlEncode();
^^^^^^^^^^^^^^^^
help: check the member name and the receiver type; hover the value to see its typeurlDecode()
Decodes a percent-encoded string back to its original form.
urlDecode(): stringconst encoded: string = "hello%20world";
const decoded: string = encoded.urlDecode(); // "hello world"
const special: string = "TitenQ%20%26%20friends";
const result: string = special.urlDecode(); // "TitenQ & friends"error
const flag: boolean = true;
const decoded: string = flag.urlDecode(); error[E0599]: no method named `urlDecode` for type `boolean`
at /src/main.tyr:2:25
const decoded: string = flag.urlDecode();
^^^^^^^^^^^^^^^^
help: check the member name and the receiver type; hover the value to see its typePattern matching
match()
Matches the string against a regular expression and returns captured groups.
match(pattern: Regex): string[]?const text: string = "order-123";
const result: string[]? = text.match(/^order-(\d+)$/);
if (result) {
const orderId: string = result[0]; // "order-123"
const digits: string = result[1]; // "123"
}error
const text: string = "order-123";
const result: string[]? = text.match("order"); error[E0308]: type mismatch for `match`: expected `Regex`, found `string`
at /src/main.tyr:2:27
const result: string[]? = text.match("order");
^^^^^^^^^^^^^^^^^^^
help: change the value or the annotation so their types match; convert numbers explicitly with `value as <type>`matchAll()
Finds all matches of a regular expression in the string.
matchAll(pattern: Regex): string[][]?const text: string = "a1 b2 c3";
const matches: string[][]? = text.matchAll(/[a-z]\d/g);
if (matches) {
for (const match of matches) {
print(match[0]); // "a1", "b2", "c3"
}
}error
const text: string = "a1 b2 c3";
const matches: string[][]? = text.matchAll("[a-z]"); error[E0308]: type mismatch for `matchAll`: expected `Regex`, found `string`
at /src/main.tyr:2:30
const matches: string[][]? = text.matchAll("[a-z]");
^^^^^^^^^^^^^^^^^^^^^^
help: change the value or the annotation so their types match; convert numbers explicitly with `value as <type>`Iteration
chars()
Iterates over the characters of the string.
chars(): char[]const emoji: string = "hello";
for (const letter of emoji.chars()) {
print(letter); // "h", "e", "l", "l", "o"
}error
const value: i32 = 42;
for (const letter of value.chars()) {
}error[E0599]: no method named `chars` for type `i32`
at /src/main.tyr:2:22
for (const letter of value.chars()) {
^^^^^^^^^^^^^
help: check the member name and the receiver type; hover the value to see its typegraphemes()
Iterates over the string's grapheme clusters, the characters a reader perceives, where one cluster may hold several scalar values.
graphemes(): string[]const astronaut: string = "a👨🚀é";
for (const cluster of astronaut.graphemes()) {
print(cluster); // "a", "👨🚀", "é"
}
print(astronaut.chars().length); // 5, scalar values
print(astronaut.graphemes().length); // 3, clustersWorking with Numbers
parseInt
Parses a string and returns an optional integer. Returns empty when the input is not a valid integer representation.
parseInt(value: string): i64?const count: i64? = parseInt("42 items"); // 42
const port: i32? = parseInt("8080"); // 8080
const overflow: i64? = parseInt("9999999999"); // value
const negative: u32? = parseInt("-5"); // emptyparseFloat
Parses a string and returns an optional floating-point number. Returns empty when the input is not a valid float representation.
parseFloat(value: string): f64?const ratio: f64? = parseFloat("3.14"); // 3.14
const scientific: f64? = parseFloat("1.5e3"); // 1500.0
const invalid: f64? = parseFloat("abc"); // emptytoString
Converts a value to its string representation.
toString(): stringconst number: i32 = 42;
const text: string = number.toString(); // "42"
const flag: boolean = true;
const label: string = flag.toString(); // "true"Regex Integration
Strings work natively with the Regex type:
const text: string = "error: file not found";
const hasError: boolean = text.includes("error"); // true
const firstSpace: i64 = text.indexOf(" "); // 5
const afterColon: string = text.substring(firstSpace + 1);
// "file not found"
const matched: string[]? = text.match(/error: (.+)/);
if (matched) {
const message: string = matched[1]; // "file not found"
}
const replaced: string = text.replace("error", "warning");
// "warning: file not found"
const parts: string[] = text.split(" ");
// ["error:", "file", "not", "found"]String literals are not char A multi-character string literal cannot be assigned to char:
error
const letter: char = "ab"; error
error[E0708]: a `char` holds exactly one character, but `ab` has 2
at /src/main.tyr:1:22
const letter: char = "ab";
^^^^
help: annotate the value with `string` to hold text of any length, or keep a single character