I did some benchmarks for some solutions in this post and got these results (if performance is important):
Fastest Method (answer from @Hans Olsson):
string str = "My Test String";
int index = str.IndexOf(' ');
index = str.IndexOf(' ', index + 1);
string result = str.Substring(0, index);
@Guffa added a one-liner for this solution (and explained bit by bit of what's going on), which I personally prefer.
Methods checked:
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());
}
Method execution times with 100000 runs
using OP's input:
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)
using a slightly longer input (spaces far into the string):
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)