【问题标题】:spliting 6 digit int into 3 parts?将 6 位整数分成 3 部分?
【发布时间】:2011-02-14 22:50:21
【问题描述】:

我想按用户获取一个六位数字并将其分成 3 部分(日、月、年)

示例:

int date=111213;
day =11;
month =12;
year =13;

我想我必须将它转换成 string 然后使用 substring() 我可以做到这一点。

任何简单的想法?

【问题讨论】:

  • 2010 年 1 月 1 日的日期如何以原始整数表示?
  • 还是 2001 年 1 月的第一天?

标签: c# split


【解决方案1】:

怎么样:

// Assuming a more sensible format, where the logically most significant part
// is the most significant part of the number too. That would allow sorting by
// integer value to be equivalent to sorting chronologically.
int day = date % 100;
int month = (date / 100) % 100;
int year = date / 10000;

// Assuming the format from the question (not sensible IMO)
int year = date % 100;
int month = (date / 100) % 100;
int day = date / 10000;

(你以这样的方式存储你的数据吗?Ick。)

【讨论】:

  • 像往常一样,比光速还快 - 只是在听你在 This Developer's Life 播客上讲话 ;-) 看起来你的网络很好 ;-)
  • 有趣的是,人们如何在不阅读 Jon Skeet 答案的情况下投票。你搞错了日期和年份。
  • 糟糕,很好发现。我认为它的顺序是合理的 :) 已修复,并指出它确实不是一个好的格式。
【解决方案2】:

像这样将日期存储为整数并不理想,但如果您必须这样做 - 并且您确定数字将始终使用指定的格式 - 那么您可以轻松提取日、月和年份:

int day = date / 10000;
int month = (date / 100) % 100;
int year = date % 100;

【讨论】:

    【解决方案3】:

    你可以用模运算来做到这一点:

    int day = date / 10000;
    int month = (date / 100) % 100;
    int year = date % 100;
    

    【讨论】:

      【解决方案4】:

      这是没有优化的Java解决方案:

       final int value = 111213;
          int day;
          int month;
          int year;
      
          day = value / 10000;
          month = (value - (day * 10000)) / 100;
          year = (value - (day * 10000)) - month * 100;

      【讨论】:

      • 他显然想要一个 C# 解决方案,那你为什么要发布一个 java 解决方案?
      • @Ramhound: 两种语言的基本操作都是一样的,对我来说就像在 JAVA 中一样
      猜你喜欢
      • 1970-01-01
      • 2015-12-19
      • 2020-11-25
      • 2017-10-04
      • 1970-01-01
      • 2021-03-04
      • 2013-10-21
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多