![](/img/trans.png)
[英]Im trying to use indexof and substring to extract text from a file but the variable index is -1 all the time what is wrong?
[英]IndexOf & Substring extract the # into integer variable
我必須以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();
您正在用原始代碼截斷年份。 因此,您需要更改以下內容:
string year = dateOfbirth.Substring(index2 + 1, length / index2 / 1);
...對此:
string year = dateOfbirth.Substring(index2 + 1);
Substring的第二個參數指定應返回多少個字符。 如果您完全省略第二個參數,則Substring將僅返回所有剩余的字符(在此特定示例中有效)。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.