Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/visual-studio/8.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# IndexOf&;子字符串将#提取为整数变量_C#_Visual Studio - Fatal编程技术网

C# IndexOf&;子字符串将#提取为整数变量

C# IndexOf&;子字符串将#提取为整数变量,c#,visual-studio,C#,Visual Studio,我必须以dd/mm/yyyy的形式请求出生日期,使用IndexOf和Substring方法将数字提取到名为day、month和year的整数变量中。我运行控制台并输入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

我必须以dd/mm/yyyy的形式请求出生日期,使用IndexOf和Substring方法将数字提取到名为day、month和year的整数变量中。我运行控制台并输入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();

您正在原始代码中截断年份。因此,您需要改变这一点:

  string year = dateOfbirth.Substring(index2 + 1, length / index2 / 1);
……为此:

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

用于指定应返回多少个字符的第二个参数。如果完全忽略第二个参数,Substring将只返回所有剩余字符(在这个特定示例中有效).

您手动执行此操作而不是调用
DateTime.ParseExact
TryParseExact
的任何原因?请指定您的问题/problem@JonSkeet我猜这是家庭作业……当你要求将
/
作为分隔符时,为什么要调用
索引('-')