Перейти к содержимому
Топаздокументация
6.05.21

Поиск в документации

Спецификация 6.0

Выберите результат стрелками и нажмите Enter, чтобы открыть его.

Введите имя API, номер диагностики, правило или тему проекта.

    Загрузка →

    Библиотека · Строки

    string.byteLength

    Return the number of bytes in the UTF-8 encoding of the text.

    byteLength() -> int
    Модуль
    Строки →
    Получатель
    string
    Минимальное число аргументов
    0
    Максимальное число аргументов
    0

    Declaration and parameters

    Доступность

    Включено по умолчанию · Да

    These types are provided by the language. No module import is required.

    The declarations below describe the standard operations on built-in values.

    Получатель

    string

    Ограничения параметров

    string.codePointAt(i: int) returns Option<int>. Index i counts Unicode scalars in the order of scalars(). It never counts UTF-8 bytes.

    An index from zero to one less than the scalar count returns Some with the Unicode value of that scalar. A negative index or an index at or past the scalar count returns None(). The call does not fault for an index outside the text.

    string.byteLength() returns the number of bytes in the UTF-8 encoding of the stored scalars. Empty text returns 0. The count does not normalize text.

    string.split(sep: string) returns Array<string>. It scans the text from the start and divides it at each occurrence of sep that does not overlap an earlier occurrence.

    The pieces keep source order. Adjacent separators and separators at either end produce empty pieces. Text without sep returns one piece that holds the whole text. Empty text returns one empty piece. Joining the pieces with sep reproduces the text.

    An empty separator faults at run time with TPZ5001 at the call. Divide text into Unicode scalars with scalars() or into grapheme clusters with graphemes().

    Результат

    The declared result type is int.

    Эффекты

    Ошибки

    Result and effects

    Count the UTF-8 bytes of the stored scalars without normalization. Empty text returns 0.

    Related entries

    Strings →

    Read code points, byte counts and separated pieces

    Правилоtopaz.stdlib.contract.string-text-members.rule

    Read code points, byte counts and separated pieces

    string.codePointAt(i: int) returns Option<int>. Index i counts Unicode scalars in the order of scalars(). It never counts UTF-8 bytes.

    An index from zero to one less than the scalar count returns Some with the Unicode value of that scalar. A negative index or an index at or past the scalar count returns None(). The call does not fault for an index outside the text.

    string.byteLength() returns the number of bytes in the UTF-8 encoding of the stored scalars. Empty text returns 0. The count does not normalize text.

    string.split(sep: string) returns Array<string>. It scans the text from the start and divides it at each occurrence of sep that does not overlap an earlier occurrence.

    The pieces keep source order. Adjacent separators and separators at either end produce empty pieces. Text without sep returns one piece that holds the whole text. Empty text returns one empty piece. Joining the pieces with sep reproduces the text.

    An empty separator faults at run time with TPZ5001 at the call. Divide text into Unicode scalars with scalars() or into grapheme clusters with graphemes().

    Причина

    Text algorithms name their unit. codePointAt uses the scalar unit of scalars() and reports absence as a value, so a classifier can read the first scalar of any text without a separate length test. byteLength gives the UTF-8 size that wire formats and byte limits use. split divides text at literal separator text, while Regex.split divides it at a pattern. An empty separator marks no position, so the call faults and the program chooses a text unit explicitly.

    Read scalar values by scalar index

    main.tpzRead scalar values by scalar indexОткрыть песочницу →
    1. import std.io
    2. function show(value: Option<int>) -> string {
    3. match (value) {
    4. case Some(point) => "{point}"
    5. case None() => "none"
    6. }
    7. }
    8. let text = "a가😀"
    9. for index in ([-1, 0, 1, 2, 3]) {
    10. io.writeLine("{index}: {show(text.codePointAt(index))}")
    11. }
    Ожидаемый выводКод завершения 0
    -1: none
    0: 97
    1: 44032
    2: 128512
    3: none
    
    $ topaz run main.tpz · Целевой продукт 5.21.3
    Ожидаемый результат

    Ожидаемый результат

    Выполнение завершается. Код завершения 0.

    Ожидаемый стандартный вывод
    1. -1: none
    2. 0: 97
    3. 1: 44032
    4. 2: 128512
    5. 3: none

    Compare scalar counts with UTF-8 byte counts

    main.tpzCompare scalar counts with UTF-8 byte countsОткрыть песочницу →
    1. import std.io
    2. for text in (["", "a", "가", "😀", "a가😀"]) {
    3. io.writeLine("{text.scalars().length} {text.byteLength()}")
    4. }
    Ожидаемый выводКод завершения 0
    0 0
    1 1
    1 3
    1 4
    3 8
    
    $ topaz run main.tpz · Целевой продукт 5.21.3
    Ожидаемый результат

    Ожидаемый результат

    Выполнение завершается. Код завершения 0.

    Ожидаемый стандартный вывод
    1. 0 0
    2. 1 1
    3. 1 3
    4. 1 4
    5. 3 8

    Keep empty pieces between separators

    main.tpzKeep empty pieces between separatorsОткрыть песочницу →
    1. import std.io
    2. function show(pieces: Array<string>) -> string {
    3. "{pieces.length} [{pieces.join("|")}]"
    4. }
    5. io.writeLine(show("a,b,,c,".split(",")))
    6. io.writeLine(show("a::b".split("::")))
    7. io.writeLine(show("aaa".split("aa")))
    8. io.writeLine(show("plain".split(",")))
    9. io.writeLine(show("".split(",")))
    10. let text = ",x,"
    11. io.writeLine("{text.split(",").join(",") == text}")
    Ожидаемый выводКод завершения 0
    5 [a|b||c|]
    2 [a|b]
    2 [|a]
    1 [plain]
    1 []
    true
    
    $ topaz run main.tpz · Целевой продукт 5.21.3
    Ожидаемый результат

    Ожидаемый результат

    Выполнение завершается. Код завершения 0.

    Ожидаемый стандартный вывод
    1. 5 [a|b||c|]
    2. 2 [a|b]
    3. 2 [|a]
    4. 1 [plain]
    5. 1 []
    6. true

    Fault on an empty separator

    main.tpzFault on an empty separatorОткрыть песочницу →
    1. import std.io
    2. let separator = ""
    3. let _ = "abc".split(separator)
    4. io.writeLine("after")
    Ожидаемый выводНенулевой код завершения
    Нет стандартного вывода.
    $ topaz run main.tpz · Целевой продукт 5.21.3
    Ожидаемый результат

    Ожидаемый результат

    Этап отклонения run. Ненулевой код завершения.

    • TPZ5001 →

      stdlib-string-split-empty-separator at main.tpz:4:9

    Diagnostics

    Runtime value guard →