如何从字符串中提取子字符串,直到遇到第二个空格?

gbp*_*hvi 24 .net c# string string-parsing

我有一个像这样的字符串:

"o1 1232.5467 1232.5467 1232.5467 1232.5467 1232.5467 1232.5467"

我该如何提取"o1 1232.5467"

要提取的字符数总是不一样.因此,我想只提取直到遇到第二个空格.

Sor*_*tis 51

一个简单的方法如下:

string[] tokens = str.Split(' ');
string retVal = tokens[0] + " " + tokens[1];
Run Code Online (Sandbox Code Playgroud)


Han*_*son 20

只需使用String.IndexOf两次,如:

     string str = "My Test String";
     int index = str.IndexOf(' ');
     index = str.IndexOf(' ', index + 1);
     string result = str.Substring(0, index);
Run Code Online (Sandbox Code Playgroud)


Guf*_*ffa 9

获得第一个空间的位置:

int space1 = theString.IndexOf(' ');
Run Code Online (Sandbox Code Playgroud)

之后的下一个空间的位置:

int space2 = theString.IndexOf(' ', space1 + 1);
Run Code Online (Sandbox Code Playgroud)

获取字符串的一部分到第二个空格:

string firstPart = theString.Substring(0, space2);
Run Code Online (Sandbox Code Playgroud)

上面的代码变成了一个单行代码:

string firstPart = theString.Substring(0, theString.IndexOf(' ', theString.IndexOf(' ') + 1));
Run Code Online (Sandbox Code Playgroud)


Red*_*ter 5

s.Substring(0, s.IndexOf(" ", s.IndexOf(" ") + 1))
Run Code Online (Sandbox Code Playgroud)


Mar*_*tos 3

使用正则表达式: .

Match m = Regex.Match(text, @"(.+? .+?) ");
if (m.Success) {
    do_something_with(m.Groups[1].Value);
}
Run Code Online (Sandbox Code Playgroud)