2013-11-01 24 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];