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

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

    A straightforward approach would be the following:

    string[] tokens = str.Split(' ');
    string retVal = tokens[0] + " " + tokens[1];
    
    0 讨论(0)
  • 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);
    }
    
    0 讨论(0)
  • 2021-02-03 23:58

    Get the position of the first space:

    int space1 = theString.IndexOf(' ');
    

    The the position of the next space after that:

    int space2 = theString.IndexOf(' ', space1 + 1);
    

    Get the part of the string up to the second space:

    string firstPart = theString.Substring(0, space2);
    

    The above code put togehter into a one-liner:

    string firstPart = theString.Substring(0, theString.IndexOf(' ', theString.IndexOf(' ') + 1));
    
    0 讨论(0)
  • 2021-02-03 23:58

    I would recommend a regular expression for this since it handles cases that you might not have considered.

    var input = "o1 1232.5467 1232.5467 1232.5467 1232.5467 1232.5467 1232.5467";
    var regex = new Regex(@"^(.*? .*?) ");
    var match = regex.Match(input);
    if (match.Success)
    {
        Console.WriteLine(string.Format("'{0}'", match.Groups[1].Value));
    }
    
    0 讨论(0)
  • 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());
    
    0 讨论(0)
  • 2021-02-04 00:05
    s.Substring(0, s.IndexOf(" ", s.IndexOf(" ") + 1))
    
    0 讨论(0)
提交回复
热议问题