How do I extract a substring from a string until the second space is encountered?

gbprithvi picture gbprithvi · Apr 8, 2010 · Viewed 138.6k times · Source

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"?

The number of characters to be extracted are not the same always. Hence, I want to only extract until the second space is encountered.

Answer

Sorantis picture Sorantis · Apr 8, 2010

A straightforward approach would be the following:

string[] tokens = str.Split(' ');
string retVal = tokens[0] + " " + tokens[1];