我在这篇文章中为一些解决方案做了一些基准测试并得到了这些结果(如果性能很重要):
最快的方法(@Hans Olsson 的回答):
string str = "My Test String";
int index = str.IndexOf(' ');
index = str.IndexOf(' ', index + 1);
string result = str.Substring(0, index);
@Guffa 为这个解决方案添加了一条线(并一点一点地解释了正在发生的事情),这是我个人更喜欢的。
检查方法:
public string Method1(string str)
{
string[] tokens = str.Split(' ');
return tokens[0] + " " + tokens[1];
}
public string Method2(string str)
{
int index = str.IndexOf(' ');
index = str.IndexOf(' ', index + 1);
return str.Substring(0, index);
}
public string Method3(string str)
{
Match m = Regex.Match(str, @"(.+? .+?) ");
if (m.Success)
{
return m.Groups[1].Value;
}
return string.Empty;
}
public string Method4(string str)
{
var regex = new Regex(@"^(.*? .*?) ");
Match m = regex.Match(str);
if (m.Success)
{
return m.Groups[1].Value;
}
return string.Empty;
}
public string Method5(string str)
{
var substring = str.TakeWhile((c0, index) =>
str.Substring(0, index + 1).Count(c => c == ' ') < 2);
return new String(substring.ToArray());
}
100000 次运行的方法执行次数
使用 OP 的输入:
string value = "o1 1232.5467 1232.5467 1232.5467 1232.5467 1232.5467 1232.5467";
Method1 took 38ms (00:00:00.0387240)
Method2 took 5ms (00:00:00.0051046)
Method3 took 100ms (00:00:00.1002327)
Method4 took 393ms (00:00:00.3938484)
Method5 took 147ms (00:00:00.1476564)
使用稍长的输入(字符串中的空格):
string value = "o11232.54671232.54671232.54671232.54671232.54671232.5467o11232.54671232.54671232.54671232.54671232.54671232.5467o1 1232.5467 1232.5467 1232.5467 1232.5467 1232.5467 1232.5467";
Method1 took 71ms (00:00:00.0718639)
Method2 took 20ms (00:00:00.0204291)
Method3 took 282ms (00:00:00.2822633)
Method4 took 541ms (00:00:00.5416347)
Method5 took 5335ms (00:00:05.3357977)