30

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

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

4

14 回答 14

62

A straightforward approach would be the following:

string[] tokens = str.Split(' ');
string retVal = tokens[0] + " " + tokens[1];
于 2010-04-08T12:26:38.603 回答
25

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);
于 2010-04-08T12:26:39.640 回答
12

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));
于 2010-04-08T12:27:31.620 回答
8
s.Substring(0, s.IndexOf(" ", s.IndexOf(" ") + 1))
于 2010-04-08T12:27:48.727 回答
3

Use a regex: .

Match m = Regex.Match(text, @"(.+? .+?) ");
if (m.Success) {
    do_something_with(m.Groups[1].Value);
}
于 2010-04-08T12:26:16.960 回答
3

Something like this:

int i = str.IndexOf(' ');
i = str.IndexOf(' ', i + 1);
return str.Substring(i);
于 2010-04-08T12:28:21.587 回答
2
string testString = "o1 1232.5467 1232.5467.........";

string secondItem = testString.Split(new char[]{' '}, 3)[1];
于 2010-04-08T12:27:58.967 回答
1
 string[] parts = myString.Split(" ");
 string whatIWant = parts[0] + " "+ parts[1];
于 2010-04-08T12:27:46.860 回答
1

:P

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

我不知道这是否是最好的方法,但我有一点乐趣 linqing 它: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());

我也得到了@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);
于 2010-04-08T17:39:52.693 回答
0

像其他人所说的那样有更短的方法,但是您也可以检查每个字符,直到您自己遇到第二个空格,然后返回相应的子字符串。

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);
}
于 2010-04-08T12:31:12.797 回答
0

您可以先尝试找到 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(' ');
于 2010-04-08T12:37:21.203 回答
0

我会为此推荐一个正则表达式,因为它可以处理您可能没有考虑过的情况。

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));
}
于 2010-04-08T13:12:14.850 回答
0

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

我只是喜欢它,因为它读起来最像你真正想要做的:“在结果子字符串少于 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());
于 2010-10-21T13:42:02.660 回答
0

我在这篇文章中为一些解决方案做了一些基准测试并得到了这些结果(如果性能很重要):

最快的方法(@Hans Olsson 的回答):

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

@Guffa 为这个解决方案添加了一条线(并一点一点地解释了正在发生的事情),这是我个人更喜欢的。

检查方法:

public string Method1(string str)
{
    string[] tokens = str.Split(' ');
    return tokens[0] + " " + tokens[1];
}

public string Method2(string str)
{
    int index = str.IndexOf(' ');
    index = str.IndexOf(' ', index + 1);
    return str.Substring(0, index);
}

public string Method3(string str)
{
    Match m = Regex.Match(str, @"(.+? .+?) ");
    if (m.Success)
    {
        return m.Groups[1].Value;
    }

    return string.Empty;
}

public string Method4(string str)
{
    var regex = new Regex(@"^(.*? .*?) ");
    Match m = regex.Match(str);
    if (m.Success)
    {
        return m.Groups[1].Value;
    }

    return string.Empty;
}

public string Method5(string str)
{
    var substring = str.TakeWhile((c0, index) =>
                        str.Substring(0, index + 1).Count(c => c == ' ') < 2);
    return new String(substring.ToArray());
}

100000 次运行的方法执行次数

使用 OP 的输入:

string value = "o1 1232.5467 1232.5467 1232.5467 1232.5467 1232.5467 1232.5467";

Method1 took 38ms (00:00:00.0387240)
Method2 took 5ms (00:00:00.0051046)
Method3 took 100ms (00:00:00.1002327)
Method4 took 393ms (00:00:00.3938484)
Method5 took 147ms (00:00:00.1476564)

使用稍长的输入(字符串中的空格):

string value = "o11232.54671232.54671232.54671232.54671232.54671232.5467o11232.54671232.54671232.54671232.54671232.54671232.5467o1 1232.5467 1232.5467 1232.5467 1232.5467 1232.5467 1232.5467";

Method1 took 71ms (00:00:00.0718639)
Method2 took 20ms (00:00:00.0204291)
Method3 took 282ms (00:00:00.2822633)
Method4 took 541ms (00:00:00.5416347)
Method5 took 5335ms (00:00:05.3357977)
于 2022-03-03T11:33:25.270 回答