将长号除以10或100?

时间:2014-03-01 16:54:15

标签: c# string type-conversion

我有两个字符串,想要分开它们。据我所知,你不能分割字符串,你首先必须将它们转换为int,double,decimal,等等。现在,我的问题是字符串的长度是1000个字符或更多,所以我不能使用int(因为字符串太长而不适合它)。当我想将超过1000位的字符串除以10或100时,我该怎么办?

2 个答案:

答案 0 :(得分:3)

一种解决方案是使用支持任意长度数的类型,例如, BigInteger

但是,由于您希望除以10或100,因此十进制数的解决方案更容易。除以10的除法只不过是砍掉最后一个字符;除以100就是砍掉最后两个字符。因此,如果您的输入是字符串,则可以使用Substring来解决此问题:

string number = "124235235235"; // imagine a longer number here

// (integer) division by 10
Console.WriteLine(number.Substring(0, number.Length - 1)); // 12423523523

// (integer) division by 100
Console.WriteLine(number.Substring(0, number.Length - 2)); // 1242352352

如果你想要一个real除法,你必须找到小数点的索引,然后向左移动一个或两个位置:

string number = "123456.78901"; // imagine a longer number here
int i = number.IndexOf(".");

// division by 10
Console.WriteLine(number.Substring(0, i - 1) + "." + number.Substring(i - 1, 1) + number.Substring(i + 1)); // 12345.678901

// division by 100
Console.WriteLine(number.Substring(0, i - 2) + "." + number.Substring(i - 2, 1) + number.Substring(i + 1)); // 1234.5678901

答案 1 :(得分:0)

您可以使用代表任意大的有符号整数的BigInteger

来自MSDN:

  

BigInteger类型是一个表示一个的不可变类型   任意大整数,其理论上的值没有上限或下限   界限。 BigInteger类型的成员与那些成员紧密相似   其他整数类型(Byte,Int16,Int32,Int64,SByte,UInt16,   UInt32和UInt64类型)。这种类型与其他积分不同   .NET Framework中的类型,其范围由其表示   MinValue和MaxValue属性。

如果您对以下两个条件感到满意,可以尝试以下方法:

注1:如果您想将其除以10或100 注2:如果您想将结果作为字符串

试试这个:如果你没有小数点

string num = "12345";
int index= num.IndexOf('.');
if(index>0)
num = num.Substring(0, index);
string dividedBy10 = num.Substring(0,num.Length - 1);//gives you 1234
string dividedBy100 = num.Substring(0, num.Length - 2);//gives you 123

试试这个:如果你想要小数点。

string num = "12345";
int index= num.IndexOf('.');
if(index>0)
num = num.Substring(0,index);
string dividedBy10 = num.Insert(num.Length - 1, ".");//gives you 1234.5
string dividedBy100 = num.Insert(num.Length - 2, ".");//gives you 123.45