Search This Blog

Monday, January 25, 2010

How to convert string to integer in c# without the predefined functions or methods

Hi guys,

Here is an interesting post for you all. How to convert a string input (e.g. "123", "325", or "1346" ) to an integer without using the predefined or library functions provided by dotnet framework (or c# language library functions).

Its pretty easy one to implement once you get an idea about it.

Here is a sample code for converting string to an integer using the technique "ascii characters".


Program:

public static void Main()
{
string str = Console.ReadLine();
int j = 0;
int myNumber = 0;
string strReverse =String.Empty;
//Reverse the string
foreach (char temp in str)
{
strReverse = temp + strReverse;
}
foreach (char temp in strReverse)
{
int i = temp - 48; //Ascii character
myNumber = myNumber + i * myPower(10,j);
j++;
}
Console.WriteLine(myNumber);
Console.ReadLine();
}

public static int myPower(int i, int j)
{
 int final = 1;
for (int loop =0 ; loop < j; loop++)
final = final * i;
return final;
}

Try the above code, it works fine. I have tested it already. But if you still have any questions please post your doubts or suggestions in the comments area.

Have fun programming :)

No comments:

Post a Comment

Leave your suggession & comment...