Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unexpected behavior of Substring in C# [duplicate]

The definition of Substring() method in .net System.String class is like this

public string Substring(int startIndex) 

Where startIndex is "The zero-based starting character position of a substring in this instance" as per the method definition. If i understand it correctly, it means it will give me a part of the string, starting at the given zero-based index.

Now, if I have a string "ABC" and take substring with different indexes, I get following results.

var str = "ABC"; var chars = str.ToArray(); //returns 3 char 'A', 'B', 'C' as expected  var sub2 = str.Substring(2); //[1] returns "C" as expected var sub3 = str.Substring(3); //[2] returns "" ...!!! Why no exception?? var sub4 = str.Substring(4); //[3] throws ArgumentOutOfRangeException as expected 

Why it doesn't throw exception for case [2] ??

The string has 3 characters, so indexes are [0, 1, 2], and even ToArray(), ToCharArray() method returns 3 characters as expected! Shouldn't it throw exception if I try to Substring() with starting index 3?

like image 308
Arghya C Avatar asked Oct 02 '15 11:10

Arghya C


1 Answers

The documentation is quite explicit about this being correct behaviour:

Return value: a string that is equivalent to the substring that begins at startIndex in this instance, or Empty if startIndex is equal to the length of this instance.

Throws ArgumentOutOfRangeException if startIndex is less than zero or *greater than the length of this instance. *

In other words, taking a substring starting just beyond the final character will give you an empty string.

Your comment that you expected it to give you a part of the string is not incompatible with this. A "part of the string" includes the set of all substrings of zero length as well, as evidenced by the fact that s.substring(n, 0) will also give an empty string.

like image 64
paxdiablo Avatar answered Sep 28 '22 06:09

paxdiablo