【问题标题】:Getting the last 5 elements of a int and save the rest in another variable获取 int 的最后 5 个元素并将其余元素保存在另一个变量中
【发布时间】:2016-05-16 12:36:20
【问题描述】:

有以下输入:

int total = 41406511332;

我知道我可以使用以下方法获取 int (11332) 的最后 5 个元素:

int lastFive = Convert.ToInt16(Convert.ToString(total).Substring(Convert.ToString(total).Length - 5));

但是我怎样才能在另一个名为 rest 的变量上获取其余项目?

这意味着,我想得到以下输入:

int lastFive = 11332
int rest = 414065

编辑:不用担心 int 溢出。

提前致谢。

【问题讨论】:

    标签: c# string int


    【解决方案1】:

    你真的不需要任何字符串操作,只需使用 mod 除法:

    long total = 41406511332;
    var lastFive = total % 100000;
    var rest = total / 100000;
    

    如果您需要做很多事情,使用不同的拆分,您可以将其移至单独的函数:

    static void SplitNumber(long number, int splitAt, out long firstHalf, out long secondHalf) {
        var divisor = (long) Math.Pow(10, splitAt);            
        firstHalf = number / divisor;
        secondHalf = number % divisor;
    }
    

    这样使用:

    long total = 41406511332;
    long first, second;
    SplitNumber(total, 5, out first, out second);
    

    【讨论】:

    • 您甚至可以将100000 添加为const 或其他不需要复制的字段。
    猜你喜欢
    • 2014-12-16
    • 2016-10-01
    • 2018-01-05
    • 2015-01-11
    • 1970-01-01
    • 2012-04-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多