System.ArgumentOutOfRangeException: startIndex cannot be greater than the length of the string

I have this code. I am trying to get only the text "first program". Given that I know that the index says 25, and the total length of the string is 35.

string text="Hello world ! This is my first program"; Response.Write(text.SubString(25,35)); 

But I get a runtime error "System.ArgumentOutOfRangeException: startIndex cannot be greater than the length of the string"

+4
source share
5 answers

String.Substring Parameters:

 public string Substring( int startIndex, int length ) 

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

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

+13
source

The second argument to string.Substring() is the length, not the final offset:

 Response.Write(text.Substring(25,10)); 
+4
source

The second Substring parameter is how long you want the substring to be, and not the endpoint of the substring. 25 + 35 is out of range of the source string, so it throws an exception.

0
source

The second argument to SubString is the number of characters in the substring.

A simplified way to do this.

  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 ie endIndex // call substring Response.Write(text.Substring(startIndex,length)); 

you can perform some operation or call a function to get the start / end values โ€‹โ€‹of the index. With this approach, you are less likely to encounter any problems associated with indexes.

0
source

During this time you can use

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

0
source

Source: https://habr.com/ru/post/1402760/


All Articles