【问题标题】:IndexOf & Substring extract the # into integer variableIndexOf & Substring 将 # 提取到整数变量中
【发布时间】:2016-04-03 17:43:30
【问题描述】:

我必须以 dd/mm/yyyy 的形式询问出生日期,使用 IndexOf 和 Substring 方法将数字提取到称为日、月和年的整数变量中。我运行控制台并输入 08/04/1995 它显示 08 天、04 个月和 19 年,但我希望它显示 08 天、04 个月和 1995 年

        string dateOfbirth;
        string temp;

        Console.WriteLine("Please enter a DOB in this form dd/mm/yyyy");
        temp = Console.ReadLine();
        dateOfbirth = temp;

        int length = dateOfbirth.Length;
        int index1 = dateOfbirth.IndexOf('/');
        int index2 = dateOfbirth.IndexOf('/', index1 + 1);

        string year = dateOfbirth.Substring(index2 + 1, length / index2 / 1);
        string month = dateOfbirth.Substring(index1 + 1, index2 / index1 / 1);
        string day = dateOfbirth.Substring(0, index1);

        Console.WriteLine( day + " day " +  month + " month " +  year + " year ");

        Console.ReadLine();

【问题讨论】:

  • 您有什么理由手动执行此操作而不是调用DateTime.ParseExactTryParseExact
  • 指定您的问题/问题
  • @JonSkeet 我想这是作业.......
  • 当您要求/ 作为分隔符时,为什么要调用IndexOf('-')

标签: c# visual-studio


【解决方案1】:

您正在截断原始代码中的年份。所以你需要改变这个:

  string year = dateOfbirth.Substring(index2 + 1, length / index2 / 1);

...到这个:

  string year = dateOfbirth.Substring(index2 + 1);

Substring 的第二个参数指定应该返回多少个字符。如果您完全省略第二个参数,则 Substring 将只返回所有剩余的字符(在此特定示例中有效)。

【讨论】:

    猜你喜欢
    • 2011-08-18
    • 1970-01-01
    • 2019-12-14
    • 1970-01-01
    • 2018-08-18
    • 1970-01-01
    • 2011-01-14
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多