2014-02-07 206 views
-1

我有一個textBox1顯示文本= 01/02/2013,並且我有 字符串年,月,日。如何從另一個字符串獲取字符串值?

如何設置 年= 2013, 月= 02, 天= 01 從TextBox1的

+4

你可能會更好解析字符串作爲'DateTime',然後分析生成的對象。 –

回答

2

使用string.Split讓每個字符串

string s = "01/02/2013"; 
string[] words = s.Split('/'); 
foreach (string word in words) 
{ 
    Console.WriteLine(word); 
} 
4
var text = "01/02/2013"; 
var parts = text.Split('/'); 
var day = parts[0]; 
var month = parts[1]; 
var year = parts[2]; 
3

只要是不同的並添加不拆分字符串的解決方案,這裏是將字符串轉換爲DateTime並將信息從生成的DateTime對象中提取出來的方法。

class Program 
{ 
    static void Main(string[] args) 
    { 
     string myString = "01/02/2013"; 
     DateTime tempDate; 
     if (!DateTime.TryParse(myString, out tempDate)) 
      Console.WriteLine("Invalid Date"); 
     else 
     { 
      var month = tempDate.Month.ToString(); 
      var year = tempDate.Year.ToString(); 
      var day = tempDate.Day.ToString(); 
      Console.WriteLine("The day is {0}, the month is {1}, the year is {2}", day, month, year); 
     } 

     Console.ReadLine(); 
    } 
} 
+1

+1,我很懶,繼續前進。 –

0

試試這個正則表達式

(?<month>\d{1,2})\/(?<day>\d{1,2})\/(?<year>\d{4}) 

I/P:

2/7/2014 

O/P:

month 2 
day  7 
year 2014 

REGEX DEMO

(OR)

嘗試通過String.Split方法

string[] separators = {"-","/",":"}; 
string value = "01/02/2013"; 
string[] words = value.Split(separators, StringSplitOptions.RemoveEmptyEntries); 
foreach (void word_loopVariable in words) 
{ 
    word = word_loopVariable; 
    Console.WriteLine(word); 
} 
+0

呃...正則表達式在這裏只是大規模的矯枉過正。 –

相關問題