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

后端 未结 13 1490
温柔的废话
温柔的废话 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-03 23:56

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

提交回复
热议问题