2012-04-23 116 views
0

我需要一些建议在这里了解最简洁的方式来拆分字符串。字符串拆分。找到正确的方法来做到这一点

字符串ix像这样:00h00m00s虽然前面的nrs也可以是3或4,如000h00m00s

所以我认为我可以用一个普通的string.split做到这一点,并把最后3个做到string 1,并做3次。 (之后删除最后一个只保留nr的)

或者如果我使用正则表达式或某些东西,这会是一种更清洁(更好)的方式吗?我仍然在编码的学习期间,并想知道你对这种情况的看法。更好的方法是什么方式,为什么?

+2

这是什么?一个约会?如何DateTime.Parse()或ParseExact? – 2012-04-23 11:40:43

+0

正则表达式将是更简单的方法,这是学习Regex这个非常强大的工具的好方法。 – 2012-04-23 11:40:44

回答

2

假设您的输入匹配的格式#h#m#s其中#代表一个或多个十进制数字,您可以使用String.Split Method到输入分为四个部分,Int32.Parse Method每个前三部分的解析为一个整数和TimeSpan Structure来表示结果:

var parts = "123h45m07s".Split('h', 'm', 's'); 

// parts == { "123", "45", "07", "" } 

var result = new TimeSpan(hours: int.Parse(parts[0]), 
          minutes: int.Parse(parts[1]), 
          seconds: int.Parse(parts[2])); 

// result == {5.03:45:07} 
+0

为什么你reccomand拆分,而不是正则表达式例如? – Dante1986 2012-04-23 12:27:11

0

您可以使用正则表达式this方法:

public static string[] Split(
    string input, 
    string pattern 
) 

var result = Regex.Split(input, @"\D"); 
+1

这将丢弃数字并返回“h”,“m”和“s”。我怀疑这是OP之后的事情。你要去'\ D'吗? – 2012-04-23 11:43:59

+0

@JoeWhite。你说得对,我的意思是'D'不''d'。谢谢! – gdoron 2012-04-23 11:44:47

1

对于这一点,正则表达式可能会是最好的 - 这是一个良好定义的格式。

var match = Regex.Match(input, @"^(\d+)h(\d+)m(\d+)s$"); 
var hoursString = match.Groups[1].Value; 
var minutesString = match.Groups[2].Value; 
var secondsString = match.Groups[3].Value; 
+0

虽然把这个给出了“unsconized escape sequence” – Dante1986 2012-04-24 06:08:13

+0

@ Dante1986,谢谢 - 我的坏,我忘了逃避字符串中的反斜杠。通过更改为'@'-string来修复它。 – 2012-04-24 11:43:51

0

正则表达式是适合这项任务:

var regex = new Regex(@"^(?<hours>\d+)h(?<minutes>\d+)m(?<seconds>\d+)s$"); 
var match = regex.Match("13h44m52s"); 
if (match.Success) { 
    var hours = Int32.Parse(match.Groups["hours"].Value); 
    var minutes = Int32.Parse(match.Groups["minutes"].Value); 
    var seconds = Int32.Parse(match.Groups["seconds"].Value); 
    var timeSpan = new TimeSpan(hours, minutes, seconds); 
    // Use timeSpan ... 
} 
0

我会用这个正则表达式来确保数字的号码,你希望

var match = Regex.Match(input, "^(\d{2,})h(\d{2})m(\d{2})s$"); 
var h = match.Groups[1]; 
var m = match.Groups[2]; 
var s = match.Groups[3]; 
1
var fields = input.Split(new[] { "h", "m" , "s" }, 
        StringSplitOptions.RemoveEmptyEntries); 
相关问题