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

前端 未结 10 1284
耶瑟儿~
耶瑟儿~ 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:34

    This is the solution I always use:

        public static string numberBaseChars = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";
    
        public static string IntToStringWithBase(int n, int b) {
            return IntToStringWithBase(n, b, 1);
        }
    
        public static string IntToStringWithBase(int n, int b, int minDigits) {
            if (minDigits < 1) minDigits = 1;
            if (n == 0) return new string('0', minDigits);
            string s = "";
            if ((b < 2) || (b > numberBaseChars.Length)) return s;
            bool neg = false;
            if ((b == 10) && (n < 0)) { neg = true; n = -n; }
            uint N = (uint)n;
            uint B = (uint)b;
            while ((N > 0) | (minDigits-- > 0)) {
                s = numberBaseChars[(int)(N % B)] + s;
                N /= B;
            }
            if (neg) s = "-" + s;
            return s;
        }
    

    This looks quite complicated but has the following features:

    • Supports radix 2 to 36
    • Handles negative values
    • Optional total number of digits

提交回复
热议问题