Best solution for an StringToInt function in C#

Posted by StefanE on Stack Overflow See other posts from Stack Overflow or by StefanE
Published on 2010-05-31T12:27:01Z Indexed on 2010/05/31 12:33 UTC
Read the original article Hit count: 219

Filed under:

Hi,

I were asked to do an StringToInt / Int.parse function on the white board in an job interview last week and did not perform very good but I came up with some sort of solution. Later when back home I made one in Visual Studion and I wonder if there are any better solution than mine below.

Have not bothred with any more error handling except checking that the string only contains digits.

        private int StrToInt(string tmpString)
    {
        int tmpResult = 0;

        System.Text.Encoding ascii = System.Text.Encoding.ASCII;
        byte[] tmpByte = ascii.GetBytes(tmpString);

        for (int i = 0; i <= tmpString.Length-1; i++)
        {
            // Check whatever the Character is an valid digit
            if (tmpByte[i] > 47 && tmpByte[i] <= 58)
                // Here I'm using the lenght-1 of the string to set the power and multiply this to the value
                tmpResult += (tmpByte[i] - 48) * ((int)Math.Pow(10, (tmpString.Length-i)-1));
            else
                throw new Exception("Non valid character in string");

        } 

        return tmpResult;
    }

© Stack Overflow or respective owner

Related posts about c#