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

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

    Something like this:

    int i = str.IndexOf(' ');
    i = str.IndexOf(' ', i + 1);
    return str.Substring(i);
    
    0 讨论(0)
  • 2021-02-03 23:44

    Just use String.IndexOf twice as in:

         string str = "My Test String";
         int index = str.IndexOf(' ');
         index = str.IndexOf(' ', index + 1);
         string result = str.Substring(0, index);
    
    0 讨论(0)
  • 2021-02-03 23:45

    Use a regex: .

    Match m = Regex.Match(text, @"(.+? .+?) ");
    if (m.Success) {
        do_something_with(m.Groups[1].Value);
    }
    
    0 讨论(0)
  • 2021-02-03 23:45
    string testString = "o1 1232.5467 1232.5467.........";
    
    string secondItem = testString.Split(new char[]{' '}, 3)[1];
    
    0 讨论(0)
  • 2021-02-03 23:53
     string[] parts = myString.Split(" ");
     string whatIWant = parts[0] + " "+ parts[1];
    
    0 讨论(0)
  • 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);
    
    0 讨论(0)
提交回复
热议问题