System.ArgumentOutOfRangeException: startIndex cannot be larger than length of string

前端 未结 5 1998
野趣味
野趣味 2020-12-18 03:25

I have this code. I am trying to retrieve just the text \"first program\". Considering that i know the index say 25 and total length of string is 35.

string          


        
相关标签:
5条回答
  • 2020-12-18 04:06

    During this time you can use

    (LINQ ElementAt) and (ElementAtOrDefault) method. However the ElementAt extension method would throw the System.ArguementOutOfRangeException when the specified index is a negative value or not less than the size of the sequence .

    0 讨论(0)
  • 2020-12-18 04:18

    Second argument for SubString is the number of characters in the substring.

    Simpler way to do it.

    int startIndex = 25; // find out startIndex
    int endIndex = 35;   // find out endIndex, in this case it is text.Length;
    int length = endIndex - startIndex; // always subtract startIndex from the position wherever you want your substring to end i.e. endIndex
    
    // call substring
    Response.Write(text.Substring(startIndex,length));     
    

    you can do some operation or call a function to get start/end index values. With this approach you are less likely to get into any trouble related to indexes.

    0 讨论(0)
  • 2020-12-18 04:25

    The parameters for String.Substring are:

    public string Substring(int startIndex, int length)
    

    You're trying to take 35 characters after the 26th character (startIndex is zero-based), which is out of range.

    If you just want to get from the 25th character to the end of the string use text.SubString(24)

    0 讨论(0)
  • 2020-12-18 04:26

    The second parameter to Substring is how long you want the substring to be, not the end point of the substring. 25 + 35 is outside the range of the original string, so it throws an exception.

    0 讨论(0)
  • 2020-12-18 04:27

    Second argument to string.Substring() is the length, not the end-offset:

    Response.Write(text.Substring(25, 10));
    
    0 讨论(0)
提交回复
热议问题