What are type conversions between integer and string in Dlang?
Overview
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 conversions
Although 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.
Syntax
to!dataType(value)
Return value
This method returns the converted value with a new data type.
Parameters
In the syntax above:
dataType: The data type we wish to convert our value to. To convert to an integerdataTypewill beintand to a string it will bestringvalue: The variable to be converted to another data type.
Code
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);}
Explanation
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.convfor the type conversion. -
Lines 7 and 8: We define the values to be converted.
-
Lines 11 and 12: We use the statements
to!intand1to!stringfor type conversion fromstringtointandinttostring, respectively. The value is saved as typeautowhich allows it to take any type assigned to it. -
Lines 15 and 16: We display the variable types of
strConvandintConvusing thetypeofbuilt-in method.