DLang integer string to another

D conversion language type is very convenient, as long as the introduction of the standard library of std.convpacket types can be converted.

Look converted to type int Integer Examples string String type:

import std.conv : to;
improt std.stdio : writeln;

void main()
{
    int i = 123;

    string s = i.to!string;
    writeln(s); // 这时候 s 就是字符串 "123"
}

Look converts string type as an example of integer type int:

import std.conv : to;
improt std.stdio : writeln;

void main()
{
    string s = "123";

    int i = s.to!int;
    writeln(i); // 这时候 i 就是整数 123

    i++;
    writeln(i); // 这时候 i 自然加一后成了 124
}

But this time there is a problem to note that if the string sis not a numeric type, this conversion will burst anomaly, this time we need to determine if non-numeric string value will be set 0.

Plus a look at the code after the judgment:

import std.conv : to;
improt std.stdio : writeln;
import std.string : isNumeric;

void main()
{
    string s1 = "123"; // 可以正常转换为 int
    string s2 = "asdf1234"; // 不可以正常转换为 int

    int a, b;

    if (isNumeric(s1))
    {
        a = s1.to!int;
    }
    else
    {
        a = 0;
    }

    if (isNumeric(s2))
    {
        b = s2.to!int;
    }
    else
    {
        b = 0;
    }

    writeln(a); // 这时候 a 就是整数 123
    writeln(b); // 这时候 b 输出的结果就是 0
}

Original: DLang integer string to another

Guess you like

Origin blog.51cto.com/197654/2452658