Fast and clever way to get the NON FIRST segment of a C# string

前端 未结 6 2404
太阳男子
太阳男子 2021-02-18 21:22

I do a split(\' \') over an string and I want to pull the first element of the returned string in order to get the rest of the string.

f.e. \"THIS IS

6条回答
  •  一个人的身影
    2021-02-18 22:01

    var a = "THIS IS AN AMAZING STRING".Split(' ');
    string amazing = String.Join(" ", a.Skip(1));
    

    If you are on pre-.NET 4, you need to stick a .ToArray() in the end of the Skip call - because the String.Join overload that takes enumerable as the second parameter was first added in .NET 4.

    While this works well in the general case, if you always want to remove just the first word, there is a better way of doing this, as pointed out by Reed in comments:

    var a = "THIS IS AN AMAZING STRING".Split(new char[] {' ' }, 2);
    string amazing = a[1];  //Perhaps do a length check first if you are not sure there is a space in the original string.
    

    This performs better for larger strings, since Split only need to look until it finds the first space, and can then create a result with two strings only - and it avoids the String.Join which could also be expensive, especially for longer strings.

提交回复
热议问题