Sponsored Ad

Friday, February 25, 2011

Interview Questions: Convert a String into Integer Without Using any Inbuilt Function in C#?

Some ask me in a interview and i searched on number of forums and at last i get to a conclusion that the best way is to use boxing. The sample and running C# code is given below.

 

using System;

namespace MyApp
{
    class my_class
    {
        static void Main(string[] args)
        {
            string strNumber = "1350";
            int intNumber = 0;
            try
            {
                foreach (char str in strNumber)
                {
                    intNumber += (int)str * 10;
                }            
                Console.WriteLine("Converted Number is: {0}", strNumber);
            }
            catch (Exception ex)
            {
                Console.WriteLine("Unable to Convert string to Number");
            }
            Console.ReadLine();
        }
    }
}

1 comment:

Sponsored Ad

Followers

Follow Us