Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Best solution for an StringToInt function in C#

Tags:

c#

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;
    }
like image 650
StefanE Avatar asked Nov 28 '22 01:11

StefanE


2 Answers

I'll take a contrarian approach.

public int? ToInt(this string mightBeInt)
{
    int convertedInt;
    if (int.TryParse(mightBeInt, out convertedInt))
    {
        return convertedInt;
    }
    return null;
}

After being told that this wasn't the point of the question, I'd argue that the question tests C coding skills, not C#. I'd further argue that treating strings as arrays of characters is a very bad habit in .NET, because strings are unicode, and in any application that might be globalized, making any assumption at all about character representations will get you in trouble, sooner or later. Further, the framework already provides a conversion method, and it will be more efficient and reliable than anything a developer would toss off in such a hurry. It's always a bad idea to re-invent framework functionality.

Then I would point out that by writing an extension method, I've created a very useful extension to the string class, something that I would actually use in production code.

If that argument loses me the job, I probably wouldn't want to work there anyway.

EDIT: As a couple of people have pointed out, I missed the "out" keyword in TryParse. Fixed.

like image 75
Cylon Cat Avatar answered Dec 18 '22 06:12

Cylon Cat


Converting to a byte array is unnecessary, because a string is already an array of chars. Also, magic numbers such as 48 should be avoided in favor of readable constants such as '0'. Here's how I'd do it:

int result = 0;
for (int i = str.Length - 1, factor = 1; i >= 0; i--, factor *= 10)
    result += (str[i] - '0') * factor;

For each character (starting from the end), add its numeric value times the correct power of 10 to the result. The power of 10 is calculated by multiplying it with 10 repeatedly, instead of unnecessarily using Math.Pow.

like image 38
Matti Virkkunen Avatar answered Dec 18 '22 05:12

Matti Virkkunen