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

前端 未结 5 2001
野趣味
野趣味 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: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.

提交回复
热议问题