我如何把一个Int在C#中的字符串不使用的ToString()? [英] How do I convert an Int to a String in C# without using ToString()?
问题描述
转换以下int参数转换为字符串,而无需使用任何原生的toString功能。
公开字符串整数到字符串(INT integerPassedIn){这里
//你的代码
}
块引用>
由于一切从继承
对象
和对象
有一个的ToString ()
方法,你会如何转换成一个INT
到字符串
不使用本机的ToString()
方法?
与字符串连接的问题是,它会调用
的ToString( )
链向上,直到遇到一个或击中对象
类。
如何你转换成整数在C#中的字符串,而无需使用
的ToString()
?
解决方案事情是这样的:
公共字符串IntToString(int类型的)
{
变种字符=新[] {0,1,2,3,4,5,6,7,8,9};
无功海峡=的String.Empty;
如果(A == 0)
{
海峡=字符[0];
}
,否则如果(A == int.MinValue)
{
海峡=-2147483648
}
,否则
{
布尔isNegative =(一个℃,);
如果(isNegative)
{
A = -a;
}
而(一个大于0)
{
海峡=字符[一%10] + STR;
A / = 10;
}
如果(isNegative)
{
海峡= - + STR;
}
}
返回海峡;
}
更新: 这是另一个版本,这是短,应该执行好得多,因为它消除了有利于操纵一个固定长度的数组的所有字符串连接。它支持基地多达16个,但它会很容易把它扩大到更高的基地。这也许可以进一步改进:
公共字符串IntToString(INT一个,诠释基数)
{
VAR字符=0123456789ABCDEF.ToCharArray();
无功海峡=新的char [32]; //任何基地
变种字符的最大数量I = str.Length;
布尔isNegative =(一个℃,);
如果(A< = 0)//处理0和int.MinValue特殊情况下,
{
海峡[ - 我] =字符[ - (一%基数);
A = - (一个/基数);
}
而(一个!= 0)
{
海峡[ - I] =字符[一%基数];
A / =基数;
}
如果(isNegative)
{
海峡[ - 我] =' - ';
}
返回新的字符串(STR,我,str.Length - 我);
}
Convert the following int argument into a string without using any native toString functionality.
public string integerToString(int integerPassedIn){ //Your code here }
Since everything inherits from
Object
andObject
has aToString()
method how would you convert anint
to astring
without using the nativeToString()
method?The problem with string concatenation is that it will call
ToString()
up the chain until it hits one or hits theObject
class.How do you convert an integer to a string in C# without using
ToString()
?解决方案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); }
这篇关于我如何把一个Int在C#中的字符串不使用的ToString()?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!