gpt4 book ai didi

c# - 如何在不使用 ToString() 的情况下在 C# 中将 Int 转换为 String?

转载 作者:IT王子 更新时间:2023-10-29 03:46:48 26 4
gpt4 key购买 nike

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

public string integerToString(int integerPassedIn){    
//Your code here
}

既然一切都继承自 Object 并且 Object 有一个 ToString() 方法,那么你如何转换一个 intstring 而不使用 native ToString() 方法?

字符串连接的问题在于它会沿链调用 ToString() 直到它命中一个或命中 Object 类。

如何在不使用 ToString() 的情况下在 C# 中将整数转换为字符串?

最佳答案

像这样:

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;
}

更新:这是另一个更短且性能更好的版本,因为它消除了所有字符串连接,有利于操作固定长度的数组。它最多支持 16 个基数,但很容易将其扩展到更高的基数。它可能会进一步改进:

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);
}

关于c# - 如何在不使用 ToString() 的情况下在 C# 中将 Int 转换为 String?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17575375/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com