I have a string like this:
\"o1 1232.5467 1232.5467 1232.5467 1232.5467 1232.5467 1232.5467\"
How do I extract only \"o1 1232.5467\"
?
A straightforward approach would be the following:
string[] tokens = str.Split(' ');
string retVal = tokens[0] + " " + tokens[1];
There are shorter ways of doing it like others have said, but you can also check each character until you encounter a second space yourself, then return the corresponding substring.
static string Extract(string str)
{
bool end = false;
int length = 0 ;
foreach (char c in str)
{
if (c == ' ' && end == false)
{
end = true;
}
else if (c == ' ' && end == true)
{
break;
}
length++;
}
return str.Substring(0, length);
}
Get the position of the first space:
int space1 = theString.IndexOf(' ');
The the position of the next space after that:
int space2 = theString.IndexOf(' ', space1 + 1);
Get the part of the string up to the second space:
string firstPart = theString.Substring(0, space2);
The above code put togehter into a one-liner:
string firstPart = theString.Substring(0, theString.IndexOf(' ', theString.IndexOf(' ') + 1));
I would recommend a regular expression for this since it handles cases that you might not have considered.
var input = "o1 1232.5467 1232.5467 1232.5467 1232.5467 1232.5467 1232.5467";
var regex = new Regex(@"^(.*? .*?) ");
var match = regex.Match(input);
if (match.Success)
{
Console.WriteLine(string.Format("'{0}'", match.Groups[1].Value));
}
I was thinking about this problem for my own code and even though I probably will end up using something simpler/faster, here's another Linq solution that's similar to one that @Francisco added.
I just like it because it reads the most like what you actually want to do: "Take chars while the resulting substring has fewer than 2 spaces."
string input = "o1 1232.5467 1232.5467 1232.5467 1232.5467 1232.5467 1232.5467";
var substring = input.TakeWhile((c0, index) =>
input.Substring(0, index + 1).Count(c => c == ' ') < 2);
string result = new String(substring.ToArray());
s.Substring(0, s.IndexOf(" ", s.IndexOf(" ") + 1))