我有一个字符串,可以输入为{n}d {n}h {n}m {n}s
,其中{n}
是一个整数,表示天数,小时数,分钟数,秒数。我如何从字符串中提取这个{n}
号码?解析字符串的整数部分
用户不必输入全部4-d,h,m,s。他只能输入4d,即4天或5h 2s,即5小时2秒。
这是我的。肯定应该有更好的方法来做到这一点。此外,并不涵盖所有情况。
int d; int m; int h; int sec;
string [] split = textBox3.Text.Split(new Char [] {' ', ','});
List<string> myCollection = new List<string>();
foreach (string s in split)
{
d = Convert.ToInt32(s.Substring(0,s.Length-1));
h = Convert.ToInt32(split[1].Substring(1));
m = Convert.ToInt32(split[2].Substring(1));
sec = Convert.ToInt32(split[3].Substring(1));
}
dt =new TimeSpan(h,m,s);
指定'RegexOptions.ExplicitCapture'而不是使用非捕获组,并且你很好... – Lucero
@Lucero:哇,我学到了一些东西新! –