Strings and integers are the most commonly used data types in software programs. Many languages provide ways to make the conversion of values between these two data types very easy.
In Dlang, a method called to!
is part of std.conv
module. So, to use this method, we’ll import this module.
string
and integer
conversionsAlthough there are other methods that can be used to convert from one data type to another in D language. But using to!
is simple especially if we want to make conversions between string
and int
.
to!dataType(value)
This method returns the converted value with a new data type.
In the syntax above:
dataType
: The data type we wish to convert our value to. To convert to an integer dataType
will be int
and to a string it will be string
value
: The variable to be converted to another data type.Let’s look at the code below:
import std.stdio;import std.conv;void main(){// define a string and an int variablestring name = "10";int height = 500;//convertingauto strConv = to!int(name);auto intConv = to!string(height);// printing to display the type of each new variablewriteln("type: ", typeof(strConv).stringof);writeln("type: ", typeof(intConv).stringof);writeln("type: ", intConv);}
In the above code, a string
is converted to an integer
and an integer
to a string
value:
Lines 1 and 2: We import necessary modules using the std.conv
for the type conversion.
Lines 7 and 8: We define the values to be converted.
Lines 11 and 12: We use the statements to!int
and 1to!string
for type conversion from string
to int
and int
to string
, respectively. The value is saved as type auto
which allows it to take any type assigned to it.
Lines 15 and 16: We display the variable types of strConv
and intConv
using the typeof
built-in method.