2017-03-05 104 views
-1

我有一个字符串,我想要得到这个子字符串。 [10:30到11:30]。如何在C#中拆分字符串

我不知道该怎么做。 strong text

string a =“这是我的字符串,在-10:30到11:30-”;

回答

1

您需要使用IndexOfLastIndexOf来获取第一个和最后一个破折号。

var firstDash = a.IndexOf("-"); 
var lastDash = a.LastIndexOf("-"); 

var timePeriod = a.Substring(firstDash + 1, lastDash - 1); 

应该是这样。如果我错过了字符串方法的阅读开始位置,请使用+1和-1。

您可能还想检查firstDashlastDash的结果。如果它们中的任何一个的值是-1,则找不到目标字符串或字符。

+0

谢谢Husein Roncevic。这很棒。 –

1

你可以使用正则表达式得到你想要的字符串。尝试下面的代码来做到这一点。
正则表达式例子:Regex Test Link

CODE:

using System; 
using System.Text.RegularExpressions; 

public class Program 
{ 
    public static void Main() 
    { 
     string a = "This is my string at -10:30 to 11:30-"; 
     string pat = @"[0-9]{2}:[0-9]{2}\sto\s[0-9]{2}:[0-9]{2}"; 

     // Instantiate the regular expression object. 
     Regex r = new Regex(pat, RegexOptions.IgnoreCase); 

     // Match the regular expression pattern against a text string. 
     Match m = r.Match(a); 
     if(m.Success){ 
      Console.WriteLine(m.Value); 
     } 
     else 
     { 
      Console.WriteLine("Nothing"); 
     }  
    } 
} 
0

让我给你最简单的代码。正则表达式与上面相同。

String result = Regex.Match(a, "[0-9]{2}:[0-9]{2}\s*to\s*[0-9]{2}:[0-9]{2}").ToString();