Tutorial on How to Convert String To Int In C#. You will Learn Multiple Conversion Methods Like Parse, TryParse & Convert Based on The Requirements:
Most of us have been in this situation once in a while when we need to convert a String into an integer data type.
For Example, let say I receive a string “99” from a data source (from the database, user input, etc) but we need it as an integer to perform some calculations, here, we will first need to convert it into an integer before we start some arithmetic operations.
There are several ways to do this, and let’s have look at a few of the widely used methods.
=> Check Out The Full C# Training Series Here
Table of Contents:
Int.Parse Method
Int.Parse method works like wonders if you are sure that your conversion will never throw an error. This is one of the easiest and simplest way to convert a string to an integer. It may throw an error if the conversion is not successful.
This method is mainly used when you have an integer in the form of string. For Example, you receive a string numeral from a user input like “99”. Let’s try a simple program to convert this string into an integer.
Program
public class Program
{ public static void Main() { String str = "99"; int number = int.Parse(str); Console.WriteLine(number); } }
Output
The output of the above program:
99
Explanation
The program will return the numerical value of the string.
The tricky part of using the int.Parse method is the problem of throwing an error if the string is not in a correct format i.e. if a string contains any characters other than numerals.
If any character other than numeral is present then this method will throw the following error:
“[System.FormatException: Input string was not in a correct format.]”
System.Convert Method
Another way to convert a string to integer is by using the Convert method. This method is not as simple as the previous method as we have to be ready to handle any exception that may occur due to the program interacting with erroneous data.
Exceptions can also consume a lot of memory, hence it’s not advisable to encounter any wanted or unwanted exception during the execution flow. For Example, if an exception occurs in a loop then a lot of memory will be consumed in throwing them and hence it will slow down your program.
Using the Convert method is quite helpful if you want to know the reason behind the failure of the parse. It can catch the exception and show the failure details.
Program
public class Program { public static String intString = "123"; public static void Main(string[] args) { int i = 0; try { i = System.Convert.ToInt32(intString); } catch (Exception e) { } Console.WriteLine("The converted int is : "+i); } }
Output
“The converted int is : 123”
Explanation
In the above program, we used the convert method to convert a string into an integer. Here if the String variable is numeral, then it will be converted into integer but in case of an erroneous string and it will throw up an exception that will be handled by the catch block.
int.TryParse Method
One of the most common ways to parse a string representation into a 32-bit integer is by using the TryParse method. This method doesn’t consider any blank space before or after the string but all the other string characters should be of an appropriate numeric type to facilitate a conversion.
For example, any white space, alphabet or special character within the variable can cause an error.
TryParse method accepts two parameters, the first one is the string that the user wants to convert and the second parameter is the keyword “out” followed by the variable in which you want to store the value. It will return a value based on the success or failure of the conversion.
TryParse(String, out var)
Let’s have a look at a simple program to convert a numeric string to an integer.
Program
class Program { static void Main(string[] args) { try { string value = "999"; int numeric; bool isTrue = int.TryParse(value, out numeric); if (isTrue) { Console.WriteLine("The Integer value is " + numeric); } } catch (FormatException e) { Console.WriteLine(e.Message); } } }
Output
The Integer value is 999
Explanation
In the above program, we have used ‘TryParse’ to convert the numeric string into an integer. First, we defined a string variable that we need to convert. Then we initialized another variable “numeric” of type integer. Then we used a Boolean variable to store the return value of the try parse.
If it returns true, then it means that the string has been converted successfully into an integer. If it returns false then there is some issue with the input string. We have surrounded the whole program snippet inside the try-catch block to handle any exception that may occur.
Converting Non-Numeric String To Integer
In all the above programs we tried to convert the numeric string value into integer but in the real world scenario most of the time we have to handle strings that contains special characters, alphabets along with the numerals. If we want to get only the numeric value then it can be a little difficult.
For Example, we have a price string with a value of $100 and we need to get the price in integer. In this case, if we try to use any of the above-discussed approaches, we will get an exception.
These types of scenarios can be handled easily by using a for loop and regex after splitting a string into an array of characters.
Let’s have a look at the program:
class Program { static void Main(string[] args) { string price = "$100"; string priceNumeric = ""; for(inti =0; i<price.Length; i++) { string ch = price[i]+""; bool isTrue = System.Text.RegularExpressions.Regex.IsMatch(ch, @"\d"); if (isTrue) { priceNumeric = priceNumeric + ch; } } int priceInt = System.Convert.ToInt32(priceNumeric); Console.WriteLine("The price numeric value is : "+ priceInt); Console.ReadLine(); } }
Output
The price numeric value is :100
Explanation:
In the above piece of code, we have a price variable of the string data type. Then we define and initialize another string variable priceNumeric. The idea is to use it to hold the numeric part of the price variable.
Next, we used a for loop to check every single character in the string for numerals. To do this we first fetched the characters in variable ch by using index. Then we used regex expression to check if the character that we picked from the string matches any numeric digit or not. (“\d” expression of Regex denotes matching with a single numeric digit.).
Then we concatenate and store the numeral string into the priceNumeric variable. Once the loop is finished, all your numeric strings will be added to this variable and every other character including special characters, alphabets, etc. will be removed.
As we know this string now contains only the numeric characters, and we can directly use the convert to transform this string into an integer.
Conclusion
In this tutorial, we learned how we can convert a string into an integer. We also learned to use the different methods that can be used for conversion based on the requirement.
Suggested reading =>> How to convert String to Integer in Java And How to convert Integer to String in Java
Next, we discussed a program to convert strings with special characters or alphabets into an integer by removing the non-integer parts. This example program can be tweaked as per user requirement and can be used to retrieve numeric data from any string.
=> Read Through The C# Guide For Beginners Here