如何从字符串中提取子字符串,直到遇到第二个空格?

时间:2020-11-28 19:20:57

I have a string like this:

我有一个像这样的字符串:

"o1 1232.5467 1232.5467 1232.5467 1232.5467 1232.5467 1232.5467"

“o1 1232.5467 1232.5467 1232.5467 1232.5467 1232.5467 1232.5467”

How do I extract only "o1 1232.5467"?

如何仅提取“o1 1232.5467”?

The number of characters to be extracted are not the same always. Hence, I want to only extract until the second space is encountered.

要提取的字符数总是不一样。因此,我想只提取直到遇到第二个空格。

13 个解决方案

#1


47  

A straightforward approach would be the following:

一个简单的方法如下:

string[] tokens = str.Split(' ');
string retVal = tokens[0] + " " + tokens[1];

#2


18  

Just use String.IndexOf twice as in:

只需使用String.IndexOf两次,如:

     string str = "My Test String";
     int index = str.IndexOf(' ');
     index = str.IndexOf(' ', index + 1);
     string result = str.Substring(0, index);

#3


9  

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

#4


5  

s.Substring(0, s.IndexOf(" ", s.IndexOf(" ") + 1))

#5


4  

Use a regex: .

使用正则表达式:。

Match m = Regex.Match(text, @"(.+? .+?) ");
if (m.Success) {
    do_something_with(m.Groups[1].Value);
}

#6


3  

Something like this:

像这样的东西:

int i = str.IndexOf(' ');
i = str.IndexOf(' ', i + 1);
return str.Substring(i);

#7


1  

string testString = "o1 1232.5467 1232.5467.........";

string secondItem = testString.Split(new char[]{' '}, 3)[1];

#8


1  

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

#9


1  

:P

: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.

只是一个注释,我认为这里的大多数算法都不会检查你是否有2个或更多的空格,所以它可能会得到一个空格作为第二个单词。

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)

我不知道它是不是最好的方式,但我有一点乐趣林清它:P(好的是它让你选择你想要的空格/单词的数量)

        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

我也得到了@ ho的答案并将它变成了一个循环,所以你可以再次使用它来获得你想要的任意数量的单词: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);

#10


1  

 string[] parts = myString.Split(" ");
 string whatIWant = parts[0] + " "+ parts[1];

#11


0  

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

#12


0  

You could try to find the indexOf "o1 " first. Then extract it. After this, Split the string using the chars "1232.5467":

你可以先尝试找到indexOf“o1”。然后提取它。在此之后,使用字符“1232.5467”拆分字符串:

        string test = "o1 1232.5467 1232.5467 1232.5467 1232.5467 1232.5467 1232.5467";
        string header = test.Substring(test.IndexOf("o1 "), "o1 ".Length);
        test = test.Substring("o1 ".Length, test.Length - "o1 ".Length);
        string[] content = test.Split(' ');

#13


0  

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.

我正在为自己的代码考虑这个问题,即使我最终会使用更简单/更快的东西,这里的另一个Linq解决方案类似于@Francisco添加的解决方案。

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."

我只是喜欢它,因为它读取的内容最像您实际想做的事情:“在生成的子字符串少于2个空格时获取字符。”

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

#1


47  

A straightforward approach would be the following:

一个简单的方法如下:

string[] tokens = str.Split(' ');
string retVal = tokens[0] + " " + tokens[1];

#2


18  

Just use String.IndexOf twice as in:

只需使用String.IndexOf两次,如:

     string str = "My Test String";
     int index = str.IndexOf(' ');
     index = str.IndexOf(' ', index + 1);
     string result = str.Substring(0, index);

#3


9  

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

#4


5  

s.Substring(0, s.IndexOf(" ", s.IndexOf(" ") + 1))

#5


4  

Use a regex: .

使用正则表达式:。

Match m = Regex.Match(text, @"(.+? .+?) ");
if (m.Success) {
    do_something_with(m.Groups[1].Value);
}

#6


3  

Something like this:

像这样的东西:

int i = str.IndexOf(' ');
i = str.IndexOf(' ', i + 1);
return str.Substring(i);

#7


1  

string testString = "o1 1232.5467 1232.5467.........";

string secondItem = testString.Split(new char[]{' '}, 3)[1];

#8


1  

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

#9


1  

:P

: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.

只是一个注释,我认为这里的大多数算法都不会检查你是否有2个或更多的空格,所以它可能会得到一个空格作为第二个单词。

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)

我不知道它是不是最好的方式,但我有一点乐趣林清它:P(好的是它让你选择你想要的空格/单词的数量)

        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

我也得到了@ ho的答案并将它变成了一个循环,所以你可以再次使用它来获得你想要的任意数量的单词: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);

#10


1  

 string[] parts = myString.Split(" ");
 string whatIWant = parts[0] + " "+ parts[1];

#11


0  

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

#12


0  

You could try to find the indexOf "o1 " first. Then extract it. After this, Split the string using the chars "1232.5467":

你可以先尝试找到indexOf“o1”。然后提取它。在此之后,使用字符“1232.5467”拆分字符串:

        string test = "o1 1232.5467 1232.5467 1232.5467 1232.5467 1232.5467 1232.5467";
        string header = test.Substring(test.IndexOf("o1 "), "o1 ".Length);
        test = test.Substring("o1 ".Length, test.Length - "o1 ".Length);
        string[] content = test.Split(' ');

#13


0  

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.

我正在为自己的代码考虑这个问题,即使我最终会使用更简单/更快的东西,这里的另一个Linq解决方案类似于@Francisco添加的解决方案。

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."

我只是喜欢它,因为它读取的内容最像您实际想做的事情:“在生成的子字符串少于2个空格时获取字符。”

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