Home > Software design >  Convert string to number without built in functions
Convert string to number without built in functions

Time:12-24

I'm told to implement fucntion which takes string as a parameter and returns int. Here is how i implemented, but the question is that my implementation is ugly and would like to see other implementations of this function. According to conditions you're not allowed to use built in fucntions such tryParse, parse, or something what does all the job for you. My implementation:

private static int StringToNumber(string str)
    {
        int number = 0;
        if (str.Contains('-'))
        {
            foreach (var character in str)
            {
                if (character == '-')
                {
                    continue;
                }
                number  = character - '0';
                number *= 10;
            }
            number *= (-1);
            number /= 10;
        }
        else 
        {
            foreach (var character in str)
            {
                number *= 10;
                number  = character - '0';
            }
        }
        return number;
    }

CodePudding user response:

You can use the approach following approach to solve this as well.

    private static int StringToInt(string str)
    {
        if (string.IsNullOrWhiteSpace(str) || str.Length == 0)
        {
            //invalid input, do something
            return 0;
        }
        var num = 0;
        var sign = 1;
        if (str[0] == '-')
        {
            sign = -1;
            str = str.Substring(1);
        }
        foreach (var c in str)
        {
            switch (c)
            {
                case '0':
                    num = (num * 10);
                    break;

                case '1':
                    num = (num * 10)   1;
                    break;

                case '2':
                    num = (num * 10)   2;
                    break;

                case '3':
                    num = (num * 10)   3;
                    break;

                case '4':
                    num = (num * 10)   4;
                    break;

                case '5':
                    num = (num * 10)   5;
                    break;

                case '6':
                    num = (num * 10)   6;
                    break;

                case '7':
                    num = (num * 10)   7;
                    break;

                case '8':
                    num = (num * 10)   8;
                    break;

                case '9':
                    num = (num * 10)   9;
                    break;

                default:
                    //do something else or ignore
                    break;
            }
        }
        return num * sign;
    }

CodePudding user response:

Here is a variant combining OP's char subtraction solution and @sitholewb solution, that is somewhat optimized.

public static int StringToIntCharSubtraction(string str)
{
    if (string.IsNullOrWhiteSpace(str) || str.Length == 0)
    {
        //invalid input, do something
        return 0;
    }

    var num = 0;
    var sign = 1;
    int i = 0;

    if (str[0] == '-')
    {
        sign = -1;
        i = 1;
    }

    while (i < str.Length)
    {
        int currentNum = (str[i] - '0');

        if (currentNum > 9 || currentNum < 0)
        {
            //do something else or ignore
            continue;
        }

        num = (num * 10)   currentNum;
        i  ;
    }

    return num * sign;
}

If you are worried about performance here is benchmark.

|                       Method |  number |      Mean |     Error |    StdDev | Ratio | Rank | Allocated |
|----------------------------- |-------- |----------:|----------:|----------:|------:|-----:|----------:|
|   StringToIntCharSubtraction |  220567 |  6.310 ns | 0.0637 ns | 0.0565 ns |  0.44 |    1 |         - |
|            StringToIntSwitch |  220567 | 13.824 ns | 0.3083 ns | 0.2884 ns |  0.96 |    2 |         - |
|                    int.Parse |  220567 | 14.345 ns | 0.0883 ns | 0.0782 ns |  1.00 |    3 |         - |
|                              |         |           |           |           |       |      |           |
|   StringToIntCharSubtraction | -829304 |  6.413 ns | 0.0556 ns | 0.0492 ns |  0.45 |    1 |         - |
|            StringToIntSwitch | -829304 | 12.896 ns | 0.2711 ns | 0.2784 ns |  0.90 |    2 |         - |
|                    int.Parse | -829304 | 14.272 ns | 0.2637 ns | 0.2467 ns |  1.00 |    3 |         - |

You can even drop the first one to 3 ns if you remove the validations, but it seems too risky for me.

  •  Tags:  
  • c#
  • Related