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

后端 未结 13 1483
温柔的废话
温柔的废话 2021-02-03 23:17

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

13条回答
  •  北恋
    北恋 (楼主)
    2021-02-04 00:02

    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());
    

提交回复
热议问题