2013-02-18 48 views
1
private static string SetValue(string input, string reference) 
{ 
    string[] sentence = input.Split(' '); 
    for(int word = 0; word<sentence.Length; word++) 
    { 
     if (sentence[word].Equals(reference, StringComparison.OrdinalIgnoreCase)) 
     { 
      return String.Join(" ", sentence.subarray(word+1,sentence.Length)) 
     } 
    } 
} 

如何轻松完成sentence.subarray(word+1,sentence.Length)或以其他方式执行此操作?加入字符串数组的其余部分

+0

看看http://msdn.microsoft.com/en-us/library/bb358985.aspx – 2013-02-18 10:56:09

回答

5

String.Joinan overload专门为此:

return String.Join(" ", sentence, word + 1, sentence.Length - (word + 1)); 
+0

谢谢!我没有注意到! :D – 2013-02-18 11:11:17

0

或者,你可以为循环使用SkipWhile而不是你的。

private static string SetValue(string input, string reference) 
{ 
    var sentence = input.Split(" "); 
    // Skip up to the reference (but not the reference itself) 
    var rest = sentence.SkipWhile( 
     s => !s.Equals(reference, StringComparison.OrdinalIgnoreCase)); 
    rest = rest.Skip(1); // Skip the reference 
    return string.Join(" ", rest); 
} 
+1

不跳过其中包含谓词为真的项目? – dtb 2013-02-18 11:02:40

+0

另外,我不确定Enumerable有'Join'。您可能需要在跳过(1)后添加'ToArray'。 – 2013-02-18 11:05:35

+1

IEnumerable 有一个[Join Method](http://msdn.microsoft.com/en-us/library/system.linq.enumerable.join.aspx),但它不是[您指的连接方法](http: //msdn.microsoft.com/en-us/library/system.string.join.aspx)。但是,String.Join方法具有[重载](http://msdn.microsoft.com/en-us/library/dd783876.aspx),它需要IEnumerable 。 – dtb 2013-02-18 11:07:47

1

如果您严格寻找解决方案独立的string.join()函数的一个子,和您使用的版本的.NET的LINQ的支持,那么可能我建议:

sentence.Skip(word + 1); 
+1

我的原始答案包括一个ToArray()调用,因为.NET版本的子数组被请求。 – 2013-02-18 11:32:46

+0

只要继续编辑它,并希望没有人会为你“纠正”它。 – Rawling 2013-02-18 11:36:03

+0

我编辑自加入只需要在.NET 4.5 IEnumerable – 2013-02-18 11:45:37

1

您可以使用重载Whereindex

return string.Join(" ", sentence.Where((w, i) => i > word)); 
+0

不要这样做。 (X,I)=> I> I)给出了与'X.Skip(I + 1)'相同的结果,但效率稍低,需要花费更长的时间。 – Rawling 2013-02-18 11:22:29

+0

@Rawling:这是真的,只是另一种方法,但不要过多考虑*早熟优化*,我喜欢使用'SKip(word + 1)'的方法,这很简单。 – 2013-02-18 11:47:04

相关问题