2017-02-16 97 views
1

如何忽略第2个字串如何跳过在C#中的字符串开始2个字

,如:

String x = "hello world this is sample text"; 
在此

的前两个单词是世界你好,所以我想跳过它们,但下一次 也许这些单词不会相同,就像它们可能成为“Hakuna Matata”一样,但该程序也应该跳过它们。 P:不建议删除字符,它不会在这里工作我猜,因为我们不知道这些字的长度是多少,我们只是想跳过前两个字。并打印剩下的部分。

+2

找到第二空间,并从空格字符的第二个索引什么离开 – vu1p3n0x

+1

子串到字符串的末尾。 – David

回答

4

请试试这个代码:

String x = "hello world this is sample text"; 

    var y = string.Join(" ", x.Split(' ').Skip(2)); 

它将由空格分割字符串,跳过两个元素再加入所有元素成一个字符串。

UPDATE:

如果你有多余的空间比第一去除多余的空格和删除的话:

String x = "hello world this is sample text"; 
x = Regex.Replace(x, @"\s+", " "); 
var y = string.Join(" ", x.Split(' ').Skip(2)); 

UPDATE:

另外,为了避免多余的空格,通过建议戴(在下面的评论)我用StringSplitOptions Split()

String x = "hello  world  this is  sample text"; 
var y = string.Join(" ", x.Split((char[])null, StringSplitOptions.RemoveEmptyEntries).Select(i => i.Trim()).Skip(2)); 
+1

如果有顺序匹配字符,'String.Split(Char)'的缺省行为将导致空元素,而使用''''只会匹配空格字符。我建议使用'String.Split(null,StringSplitOptions.RemoveEmptyEntries)'代替(它匹配所有空白元素,并且不包含重复项)。 – Dai

+0

谢谢@ kat1330 –

0

我不推荐使用IndexOf,因为它在连续的空格字符的情况下不会帮助您,而使用String.Split(null)String.Join效率不高。你可以做到这一点使用正则表达式或FSM解析器:

Int32 startOfSecondWord = -1; 

Boolean inWord = false; 
Int32 wordCount = 0; 
for(int = 0; i < input.Length; i++) { 
    Boolean isWS = Char.IsWhitespace(input[i]); 
    if(inWord) { 
     if(isWS) inWord = false; 
    } 
    else { 
     if(!isWS) { 
      inWord = true; 
      wordCount++; 

      if(wordCount == 2) { 
       startOfSecondWord = i; 
       break; 
      } 
     } 
    } 
} 

if(startOfSecondWord > -1) return input.Substring(startOfSecondWord); 
+0

@Andrew如果你已经熟悉状态机的构造,这并不复杂,但我很欣赏它的第一眼看起来很吓人。这种方法的一个优点是纯粹的速度:内部分配为零,它在'O(n)'时间内运行,甚至在'Substring'调用之前甚至遍历整个字符串。 – Dai

0

使用正则表达式应该这样做:

using System; 
using System.Text.RegularExpressions; 

public class Example 
{ 
    public static void Main() 
    { 
     string input = "hello world this is sample text"; 
     string pattern = @"(\w+\s+){2}(.*)"; 
     string replacement = "$1"; 
     Regex rgx = new Regex(pattern); 
     string result = rgx.Replace(input, replacement); 

     Console.WriteLine("Original String: {0}", input); 
     Console.WriteLine("Replacement String: {0}", result);        
    } 
} 
相关问题