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

后端 未结 13 1495
温柔的废话
温柔的废话 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:57

    There are shorter ways of doing it like others have said, but you can also check each character until you encounter a second space yourself, then return the corresponding substring.

    static string Extract(string str)
    {
        bool end = false;
        int length = 0 ;
        foreach (char c in str)
        {
            if (c == ' ' && end == false)
            {
                end = true;
            }
            else if (c == ' ' && end == true)
            {
                break;
            }
    
            length++;
        }
    
        return str.Substring(0, length);
    }
    

提交回复
热议问题