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

前端 未结 6 2184
太阳男子
太阳男子 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:07

    Do NOT use the Split function - a) it looks for every ' ' symbol there is, not just the first one. b) this approach will involve lots of copying data around in memory which is rather slow operation for strings.

    var a = "THIS IS AN AMAZING STRING";
    string result;
    var index = a.IndexOf(' ');
    if (index == -1)
        result = null;
    else
        result = a.Substring(index + 1);
    

    Since the title of the question mentions array, not string, it is worth mentioning the ArraySegment class - this enables you to create a pointer to part of the array (without creating a new array and copying data):

    var a = new int[] { 0, 1, 2, 3 };
    var segment = new ArraySegment(a, 1, a.Length - 1);
    

提交回复
热议问题