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\"
?>
:P
Just a note, I think that most of the algorithms here wont check if you have 2 or more spaces together, so it might get a space as the second word.
I don't know if it the best way, but I had a little fun linqing it :P (the good thing is that it let you choose the number of spaces/words you want to take)
var text = "a sdasdf ad a";
int numSpaces = 2;
var result = text.TakeWhile(c =>
{
if (c==' ')
numSpaces--;
if (numSpaces <= 0)
return false;
return true;
});
text = new string(result.ToArray());
I also got @ho's answer and made it into a cycle so you could again use it for as many words as you want :P
string str = "My Test String hello world";
int numberOfSpaces = 3;
int index = str.IndexOf(' ');
while (--numberOfSpaces>0)
{
index = str.IndexOf(' ', index + 1);
}
string result = str.Substring(0, index);