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

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

"o1 1232.5467 1232.5467 1232.5467 1232.5467 1232.5467 1232.5467"

如何仅提取"o1 1232.5467"

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

一个简单的方法如下:

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

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

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

获得第一个空间的位置:

 int space1 = theString.IndexOf(' '); 

之后的下一个空间的位置:

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

获取字符串的一部分到第二个空格:

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

上面的代码变成了一个单行代码:

 string firstPart = theString.Substring(0, theString.IndexOf(' ', theString.IndexOf(' ') + 1)); 
 s.Substring(0, s.IndexOf(" ", s.IndexOf(" ") + 1)) 

使用正则表达式:。

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

像这样的东西:

 int i = str.IndexOf(' '); i = str.IndexOf(' ', i + 1); return str.Substring(i); 
 string testString = "o1 1232.5467 1232.5467........."; string secondItem = testString.Split(new char[]{' '}, 3)[1]; 

我会推荐一个正则表达式,因为它处理你可能没有考虑过的案例。

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

:P

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

我不知道它是不是最好的方式,但我有一点乐趣林清它: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); 
  string[] parts = myString.Split(" "); string whatIWant = parts[0] + " "+ parts[1]; 

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

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

你可以先尝试找到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(' '); 

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

我只是喜欢它,因为它读取的内容最像您实际想做的事情:“在生成的子字符串少于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());