2014-02-07 323 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

呃...正则表达式在这里只是大规模的矫枉过正。 –

相关问题