How do I convert an Int to a String in C# without using ToString()?

前端 未结 10 1278
耶瑟儿~
耶瑟儿~ 2020-12-12 13:49

Convert the following int argument into a string without using any native toString functionality.

public string integerToString(int integerPas         


        
10条回答
  •  再見小時候
    2020-12-12 14:22

    Something like this:

    public string IntToString(int a)
    {    
        var chars = new[] { "0", "1", "2", "3", "4", "5", "6", "7", "8", "9" };
        var str = string.Empty;
        if (a == 0)
        {
            str = chars[0];
        }
        else if (a == int.MinValue)
        {
            str = "-2147483648";
        }
        else
        {
            bool isNegative = (a < 0);
            if (isNegative)
            {
                a = -a;
            }
    
            while (a > 0)
            {
                str = chars[a % 10] + str;
                a /= 10;
            }
    
            if (isNegative)
            {
                str = "-" + str;
            }
        }
    
        return str;
    }
    

    Update: Here's another version which is shorter and should perform much better, since it eliminates all string concatenation in favor of manipulating a fixed-length array. It supports bases up to 16, but it would be easy to extend it to higher bases. It could probably be improved further:

    public string IntToString(int a, int radix)
    {
        var chars = "0123456789ABCDEF".ToCharArray();
        var str = new char[32]; // maximum number of chars in any base
        var i = str.Length;
        bool isNegative = (a < 0);
        if (a <= 0) // handles 0 and int.MinValue special cases
        {
            str[--i] = chars[-(a % radix)];
            a = -(a / radix);
        }
    
        while (a != 0)
        {
            str[--i] = chars[a % radix];
            a /= radix;
        }
    
        if (isNegative)
        {
            str[--i] = '-';
        }
    
        return new string(str, i, str.Length - i);
    }
    

提交回复
热议问题