The atoi
function in C# is used to convert a string representation of a number to its integer equivalent. In C#, the equivalent function is int.Parse()
or int.TryParse()
.
The following is an example of how you can use int.Parse()
to convert a string to an integer:
string numAsString = "123";
int numAsInt = int.Parse(numAsString);
And here’s an example of how you can use int.TryParse() to convert a string to an integer:
string numAsString = "123";
int numAsInt;
bool success = int.TryParse(numAsString, out numAsInt);
if (success)
{
Console.WriteLine(numAsInt);
}
else
{
Console.WriteLine("The string could not be parsed to an integer.");
}
Note that int.TryParse() is a safer option than int.Parse() as it returns a boolean value indicating whether the conversion was successful, rather than throwing an exception if the string is not a valid representation of a number.