C# 如何从另一个字符串中获取字符串值?
我有一个文本框1,显示text=01/02/2013,我有 串年、月、日 如何设置 年份=2013年, 月份=02, 日=01C# 如何从另一个字符串中获取字符串值?,c#,C#,我有一个文本框1,显示text=01/02/2013,我有 串年、月、日 如何设置 年份=2013年, 月份=02, 日=01 从textbox1使用string.Split获取每个字符串 string s = "01/02/2013"; string[] words = s.Split('/'); foreach (string word in words) { Console.WriteLine(word); } 不同的是,为了添加一个不拆分字符串的解决方案,这里有一个将字符串转换
从textbox1使用string.Split获取每个字符串
string s = "01/02/2013";
string[] words = s.Split('/');
foreach (string word in words)
{
Console.WriteLine(word);
}
不同的是,为了添加一个不拆分字符串的解决方案,这里有一个将字符串转换为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();
}
}
试试这个正则表达式
(?<month>\d{1,2})\/(?<day>\d{1,2})\/(?<year>\d{4})
O/p:
或
试一试
您最好将字符串解析为日期时间,然后分析结果对象。呃。。。正则表达式在这里简直是过度使用了。
(?<month>\d{1,2})\/(?<day>\d{1,2})\/(?<year>\d{4})
2/7/2014
month 2
day 7
year 2014
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);
}