Reputation: 335
string tmp = "Monday; 12/11/2013 | 0.23.59
How would I get date string , that is 12/11/2013. I have try this:
int sep=tmp.IndexOf(";");
int lat=tmp.IndexOf("|");
string thu = tmp.Substring(0, sep);
string tem = tmp.Substring(lat + 1);
string ngay = tmp.Substring(sep, tmp.Length - (sep+tem.Length);
Console.WriteLine("Date: {0}", ngay);
How can this be done in C#?
Upvotes: 1
Views: 95
Reputation: 142
string tmp = "Monday; 12/11/2013 | 0.23.59";
string date = tmp.Split(' ')[1];
Upvotes: 0
Reputation: 149020
The algorithm you've worked out just needs a little adjustment if you want just the date part. Try this:
string tmp = "Monday; 12/11/2013 | 0.23.59";
int sep=tmp.IndexOf(";") + 2; // note the + 2
int lat=tmp.IndexOf("|") - 2; // note the - 2
string thu = tmp.Substring(0, sep);
string tem = tmp.Substring(lat + 1);
string ngay = tmp.Substring(sep, tmp.Length - (sep+tem.Length));
Console.WriteLine("Date: {0}", ngay);
It will now output
Date: 12/11/2013
Upvotes: 4
Reputation: 50845
Try this:
string tmp = "Monday; 12/11/2013 | 0.23.59";
var dateString = tmp.Split(new [] { ';', '|' })[1].Trim();
String.Split()
allows you to specify delimiter characters so you don't have to worry about getting positional offsets (e.g. +2, -1, etc.) correct. It also allows you to remove empty entries, and (IMHO), is a little easier to read the intent of the code.
Upvotes: 2