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\"
?
Something like this:
int i = str.IndexOf(' ');
i = str.IndexOf(' ', i + 1);
return str.Substring(i);
Just use String.IndexOf twice as in:
string str = "My Test String";
int index = str.IndexOf(' ');
index = str.IndexOf(' ', index + 1);
string result = str.Substring(0, index);
Use a regex: .
Match m = Regex.Match(text, @"(.+? .+?) ");
if (m.Success) {
do_something_with(m.Groups[1].Value);
}
string testString = "o1 1232.5467 1232.5467.........";
string secondItem = testString.Split(new char[]{' '}, 3)[1];
string[] parts = myString.Split(" ");
string whatIWant = parts[0] + " "+ parts[1];
: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);