Strings
string é o tipo nativo de texto UTF-8 no tyrus. A sintaxe fonte é concisa, enquanto a implementação de runtime é nativa.
Strings com aspas
const greeting: string = "hello";
const alternative: string = 'hello';O formatter normaliza aspas conforme quote_style, exceto quando configurado como "off", que preserva as aspas e escapes originais de cada literal de string.
Strings multilinha
Uma string delimitada por """ pode ocupar várias linhas mantendo o alinhamento com o código ao redor. O compilador remove o recuo em tempo de compilação: de cada linha, ele retira tantos espaços à esquerda quanto o """ de fechamento estiver recuado, e descarta uma primeira linha deixada em branco logo após o """ de abertura. O resultado é um literal string comum, então não há custo em runtime para escrever uma query ou um template alinhado em vez de rente à margem esquerda.
const query: string = """
SELECT id, name
FROM users
WHERE active = true
""";A margem de dedent conta apenas espaços; um """ fechado numa linha recuada com tabs mede margem zero, então use espaços para o recuo que você quer remover.
Template literals
Use template literals para interpolação e texto multiline.
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: 0042Uma interpolação pode carregar um especificador de formato depois de :, .Nf fixa um float em exatamente N casas decimais, e 0Nd preenche um inteiro com zeros à esquerda até uma largura total de N caracteres. .Nf exige um valor float e 0Nd exige um valor inteiro; uma incompatibilidade é um erro de compilação (E0717) que nomeia o tipo exigido.
Um valor de tipo união também pode ser interpolado. Qual variante ele guarda é um fato de tempo de execução, então a renderização é escolhida em tempo de execução e coincide com o que o print imprimiria para aquela variante.
Tipos string literais
String literals podem participar de unions literais e tagged unions.
Uma união de literais é um valor comum: compare-a com qualquer uma de suas variantes (status === "active"), ramifique com um match que não precisa de _ quando cobre toda variante, construa uma com um ternário, junte várias num array e chame nela qualquer coisa que uma string aceite, toda variante de uma união de literais de string é uma string. A comparação é uma checagem de um byte em vez de comparação de texto, porque uma união dessas é representada por qual variante ela guarda e nada mais.
type Role = "admin" | "operator" | "viewer";
interface Success {
tag: "success";
data: string;
}Valores literais não são membros de enum
Use strings literais para pequenos domínios textuais fechados. Use enum quando o domínio precisa de membros nomeados e semântica nativa de enum.
Grupos de grafemas
O chars() devolve valores escalares Unicode; o graphemes() devolve o que um leitor chama de caracteres. Os dois diferem sempre que um caractere visível é escrito com vários valores escalares, um emoji montado com sequência de zero-width joiner, ou uma letra seguida de acento combinante.
const astronaut: string = "👨🚀";
print(astronaut.chars().length); // 3
print(astronaut.graphemes().length); // 1Indexação, fatiamento e length contam valores escalares, não grupos: essa é a unidade em que toda posição da API de string é medida, e é o que faz text.charAt(text.length - 1) ser o último. O graphemes() responde à pergunta de exibição, quantos caracteres um leitor vê, e onde um cursor pararia, e devolve string[], porque um grupo pode conter mais de um valor escalar.
Propriedades de string
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 é lido do valor, não contado: uma string carrega a contagem de caracteres junto com o texto, então perguntá-la custa o mesmo com três caracteres ou com três milhões. U+0000 é um caractere comum numa string, o texto é delimitado pelo comprimento registrado, não por um terminador, então "a\u{0}b".length é 3 e ele sobrevive inteiro a comparação, interpolação e impressão.
length conta caracteres, valores escalares Unicode, nunca os bytes UTF-8 subjacentes, então concorda com chars() em qualquer texto. Toda posição na API de string usa essa mesma unidade: charAt(), charCodeAt(), slice(), substring(), indexOf(), lastIndexOf(), padStart() e padEnd() contam caracteres, o que é o que faz text.charAt(text.length - 1) ser o último caractere de qualquer string, acentuada ou não.
Métodos
| Categoria | Métodos |
|---|---|
| Conversão de caixa | toUpperCase(), toLowerCase() |
| Transformação de caixa | toSlugCase(), toDashCase(), toKebabCase(), toPascalCase(), toCamelCase(), toSnakeCase() |
| Remoção de espaços | trim(), trimStart(), trimEnd() |
| Busca | includes(), startsWith(), endsWith(), indexOf(), lastIndexOf(), search() |
| Fatias e extração | slice(), substring(), charAt(), charCodeAt(), truncate(), truncateEllipsis() |
| Transformação | replace(), repeat(), padStart(), padEnd(), concat(), split() |
| HTML e codificação | stripHtml(), escapeHtml(), urlEncode(), urlDecode() |
| Correspondência de padrão | match(), matchAll() |
| Iteração | chars(), graphemes() |
Conversão de caixa
toUpperCase()
Retorna a string com todos os caracteres em maiúsculo.
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()
Retorna a string com todos os caracteres em minúsculo.
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 typeTransformação de caixa
toSlugCase()
Normaliza a string para um slug amigável a URLs. Remove acentos via decomposição NFKD, remove caracteres não alfanuméricos e junta palavras com hífens.
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()
Converte a string para dash-case (palavras minúsculas unidas por hífens). Tokeniza por espaços, underscores, hífens e limites de camelCase. Diferente de toSlugCase(), acentos são preservados.
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 de toDashCase().
toKebabCase(): stringconst phrase: string = "hello world example";
const kebab: string = phrase.toKebabCase(); // "hello-world-example"toKebabCase() is an alias for toDashCase().
toPascalCase()
Converte a string para PascalCase. Cada palavra é capitalizada e unida sem separadores.
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()
Converte a string para camelCase. A primeira palavra é minúscula, as demais são capitalizadas.
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()
Converte a string para snake_case (palavras minúsculas unidas por 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 typeRemoção de espaços
trim()
Remove espaços em branco de ambas as extremidades da 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()
Remove espaços em branco do início da 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()
Remove espaços em branco do final da 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 typeBusca
includes()
Verifica se a string contém uma 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()
Verifica se a string começa com uma 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()
Verifica se a string termina com uma 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()
Retorna o índice da primeira ocorrência de uma substring, ou -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()
Retorna o índice da última ocorrência de uma substring, ou -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()
Busca um padrão usando expressão regular e retorna o índice da correspondência.
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>`Fatias e extração
slice()
Extrai uma seção da string e a retorna como uma nova 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()
Retorna uma substring a partir de um índice dado.
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()
Retorna o caractere em um índice especificado.
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()
Retorna o código Unicode do caractere em um índice especificado.
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()
Trunca a string para um número máximo de 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()
Trunca a string para um número máximo de code points e anexa ... quando o texto excede o limite.
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>`Transformação
replace()
Substitui uma substring ou padrão por uma string de substituição.
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()
Retorna uma nova string com o original repetido um número dado de vezes.
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()
Preenche o início da string com um caractere de preenchimento até atingir um comprimento alvo.
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()
Preenche o final da string com um caractere de preenchimento até atingir um comprimento alvo.
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()
Concatena a string com uma ou mais strings.
Guardar uma string além do valor de onde ela veio, colocá-la num array, capturá-la numa closure, armazená-la num campo, não copia mais o texto. As duas compartilham um buffer e cada uma segura uma referência a ele, o que é seguro justamente porque uma string é imutável: dois leitores de um buffer não têm como discordar.
Uma cadeia de + custa uma alocação, não uma por operador: a + b + c + d mede todos os operandos primeiro, cada string carrega o próprio comprimento, então medir não lê nada, e só então preenche um único 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()
Divide a string em um array de substrings usando um separador.
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 e codificação
stripHtml()
Remove todas as tags HTML da string, deixando apenas o conteúdo textual. Decodifica entidades HTML comuns (<, >, &, ", ').
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()
Escapa caracteres especiais para entidades HTML (& < > " '), prevenindo injeção XSS.
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()
Codifica a string com percent-encoding para uso como parâmetro de query URL. Codifica todos os caracteres exceto caracteres não reservados (letras, dígitos, -, _, ., ~).
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()
Decodifica uma string codificada com percent-encoding de volta à sua forma original.
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 typeCorrespondência de padrão
match()
Compara a string com uma expressão regular e retorna grupos capturados.
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()
Encontra todas as correspondências de uma expressão regular na 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>`Iteração
chars()
Itera sobre os caracteres da 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()
Itera sobre os grupos de grafemas da string, os caracteres que um leitor percebe, onde um grupo pode conter vários valores escalares.
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, clustersTrabalhando com números
parseInt
Analisa uma string e retorna um inteiro opcional. Retorna vazio quando a entrada não é uma representação válida de inteiro.
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
Analisa uma string e retorna um número de ponto flutuante opcional. Retorna vazio quando a entrada não é uma representação válida de float.
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
Converte um valor para sua representação em string.
toString(): stringconst number: i32 = 42;
const text: string = number.toString(); // "42"
const flag: boolean = true;
const label: string = flag.toString(); // "true"Integração com Regex
Strings trabalham nativamente com o tipo Regex:
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"]Literais de string não são char Um literal de string com múltiplos caracteres não pode ser atribuído a 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