2013-11-01 25 views
1
string tmp = "Monday; 12/11/2013 | 0.23.59 

我如何获得日期字符串,即12/11/2013。我试试这个:如何从此获取日期字符串?

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); 

这怎么可以在C#中完成?

回答

2

试试这个:

string tmp = "Monday; 12/11/2013 | 0.23.59"; 
var dateString = tmp.Split(new [] { ';', '|' })[1].Trim(); 

String.Split()允许你,所以你不必担心会位置偏移指定分隔符(例如+2,-1,等等)是正确的。它还允许您删除空条目,(恕我直言),更容易阅读代码的意图。

+0

谢谢,但错误\t为“串的最佳重载的方法匹配。拆分(char [],System.StringSplitOptions)'有一些无效的参数 –

+0

尝试它现在写的方式。我从内存中工作,并经常得到不正确的参数。它现在已经过测试和工作。 – Yuck

4

如果您只需要日期部分,那么您已经计算出的算法只需稍作调整。试试这个:

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); 

现在它将输出

日期:2013年12月11日

+0

你有一个新的头像。 –

+1

@KenKin Heh,当我终于厌倦了gravatar时,我更新了它。 –

0
string tmp = "Monday; 12/11/2013 | 0.23.59"; 
      string date = tmp.Split(' ')[1];