简体   繁体   English

如何查找多个子字符串

[英]How to find multiple substrings

I have stored date of birth var char format: 我已经存储了出生日期var char格式:

Example: 1989-8-15 范例:1989-8-15

I want to find out sub string from it ie I want separate year, month and date. 我想从中找出子字符串,即我想要单独的年,月和日。 I have tried it with following code: 我已经尝试使用以下代码:

string dateOfbirth = (string)(DataBinder.Eval(e.Item.DataItem, "dob"));

int length = (dateOfbirth).Length;
int index1 = dateOfbirth.IndexOf('-');
int index2 = dateOfbirth.IndexOf('-', index1 + 1);
string year = dateOfbirth.Substring(0, index1);
string month = dateOfbirth.Substring(index+1, index2-1);
string day = dateOfbirth.Substring(index2, length);

I am getting an error. 我收到一个错误。 Please suggest a solution. 请提出解决方案。 Thanks in advance. 提前致谢。

You can try this 你可以试试这个

string [] date = dateOfbirth.Split('-');
string year = date[0];
string month = date[1];
string day = date[2];
DateTime dob = DateTime.ParseExact("1989-8-15","yyyy-M-dd",null);
Console.WriteLine(dob.Year);
Console.WriteLine(dob.Month);
Console.WriteLine(dob.Day);

Clean and easy. 干净又容易。

UPD : changed Parse to ParseExact with a custom date format UPD :使用自定义日期格式将Parse更改为ParseExact

I hope this will help: 我希望这个能帮上忙:

string st= "1989-8-15"; / 
string st = (string)(DataBinder.Eval(e.Item.DataItem, "dob"));

string [] stArr = st.Split('-');

So, you now have an array with dob items. 因此,您现在有了一个包含dob项的数组。

To actually answer your question: 实际回答您的问题:

string dateOfbirth = "1989-8-15";

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

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

It's just a matter of providing the correct parameters to the Substring method. 只需为Substring方法提供正确的参数即可。

Using dateOfBirth.Split('-') would probably be at better solution for your problem, though. 不过,使用dateOfBirth.Split('-')可能是解决您问题的更好解决方案。

Use TryParseExact to avoid exception due to different culture settings 使用TryParseExact可以避免由于区域性设置不同而导致的异常

DateTime dateValue;
var dateString="1989-08-15";
if(DateTime.TryParseExact(dateString, "yyyy-MM-dd", CultureInfo.InvariantCulture,DateTimeStyles.None, out dateValue))
{
// parse successfull
Console.WriteLine(dateValue.Year);
Console.WriteLine(dateValue.Month);
Console.WriteLine(dateValue.Day);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM