C# IndexOf&;子字符串将#提取为整数变量
我必须以dd/mm/yyyy的形式请求出生日期,使用IndexOf和Substring方法将数字提取到名为day、month和year的整数变量中。我运行控制台并输入08/04/1995它显示08天、04个月和19年,但我希望它显示08天、04个月和1995年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
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我猜这是家庭作业……当你要求将/
作为分隔符时,为什么要调用索引('-')
?