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

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

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

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

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

    Загрузка →

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

    string.toInt

    Parse an optional leading minus sign and ASCII decimal digits as an int.

    toInt() -> Option<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.toInt() returns Option<int>. It accepts an optional leading - followed by one or more ASCII digits 0 through 9, and no other characters.

    Leading zeros are accepted. -0 produces 0.

    Leading or trailing whitespace, a leading +, digit separators, radix prefixes, exponents, fractions and non-ASCII digits return None(). Empty text and a lone - also return None().

    A spelled value below -9223372036854775808 or above 9223372036854775807 returns None(). The call never faults for its text.

    Call trim() before toInt() when the input format allows surrounding whitespace.

    Результат

    The declared result type is Option<int>.

    Эффекты

    Ошибки

    Result and effects

    Return None() for any other spelling and for a value outside the int range.

    Related entries

    Strings →

    Parse decimal integers with one spelling

    Правилоtopaz.stdlib.contract.string-to-int.rule

    Parse decimal integers with one spelling

    string.toInt() returns Option<int>. It accepts an optional leading - followed by one or more ASCII digits 0 through 9, and no other characters.

    Leading zeros are accepted. -0 produces 0.

    Leading or trailing whitespace, a leading +, digit separators, radix prefixes, exponents, fractions and non-ASCII digits return None(). Empty text and a lone - also return None().

    A spelled value below -9223372036854775808 or above 9223372036854775807 returns None(). The call never faults for its text.

    Call trim() before toInt() when the input format allows surrounding whitespace.

    Причина

    One number has one accepted spelling, as in BigInt and Decimal text parsing. Rejecting whitespace and a plus sign keeps malformed input visible to the program, so a reader of wire formats does not accept a value that its writer never produces.

    Parse a minus sign and decimal digits

    main.tpzParse a minus sign and decimal digitsОткрыть песочницу →
    1. import std.io
    2. function show(text: string) -> string {
    3. match (text.toInt()) {
    4. case Some(value) => "{value}"
    5. case None() => "none"
    6. }
    7. }
    8. for text in (["42", "-7", "007", "-0", "9223372036854775807", "-9223372036854775808"]) {
    9. io.writeLine("[{text}] {show(text)}")
    10. }
    Ожидаемый выводКод завершения 0
    [42] 42
    [-7] -7
    [007] 7
    [-0] 0
    [9223372036854775807] 9223372036854775807
    [-9223372036854775808] -9223372036854775808
    
    $ topaz run main.tpz · Целевой продукт 5.21.3
    Ожидаемый результат

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

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

    Ожидаемый стандартный вывод
    1. [42] 42
    2. [-7] -7
    3. [007] 7
    4. [-0] 0
    5. [9223372036854775807] 9223372036854775807
    6. [-9223372036854775808] -9223372036854775808

    Return None() for other spellings and out-of-range values

    main.tpzReturn None() for other spellings and out-of-range valuesОткрыть песочницу →
    1. import std.io
    2. function show(text: string) -> string {
    3. match (text.toInt()) {
    4. case Some(value) => "{value}"
    5. case None() => "none"
    6. }
    7. }
    8. for text in (["", "-", "12a", "1_000", "0x10", "1e3", "١٢", "9223372036854775808", "-9223372036854775809"]) {
    9. io.writeLine("[{text}] {show(text)}")
    10. }
    Ожидаемый выводКод завершения 0
    [] none
    [-] none
    [12a] none
    [1_000] none
    [0x10] none
    [1e3] none
    [١٢] none
    [9223372036854775808] none
    [-9223372036854775809] none
    
    $ topaz run main.tpz · Целевой продукт 5.21.3
    Ожидаемый результат

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

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

    Ожидаемый стандартный вывод
    1. [] none
    2. [-] none
    3. [12a] none
    4. [1_000] none
    5. [0x10] none
    6. [1e3] none
    7. [١٢] none
    8. [9223372036854775808] none
    9. [-9223372036854775809] none

    Return None() for surrounding whitespace and a plus sign

    main.tpzReturn None() for surrounding whitespace and a plus signОткрыть песочницу →
    1. import std.io
    2. function show(text: string) -> string {
    3. match (text.toInt()) {
    4. case Some(value) => "{value}"
    5. case None() => "none"
    6. }
    7. }
    8. for text in ([" 12", "12 ", "+5"]) {
    9. io.writeLine("[{text}] {show(text)}")
    10. }
    Ожидаемый выводКод завершения 0
    [ 12] none
    [12 ] none
    [+5] none
    
    $ topaz run main.tpz · Целевой продукт 5.21.3
    Ожидаемый результат

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

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

    Ожидаемый стандартный вывод
    1. [ 12] none
    2. [12 ] none
    3. [+5] none