Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# - String IndexOf method with second argument equal to String length

Tags:

c#

.net

At some point in my code, I use this method:

IndexOf(string str, int startIndex)

I am also doing some calculations before, and I invoke this method with second argument (startIndex) equal to length of a string passed as first argument. Of course, no such an index exists in a string, and if we did something like this:

string[string.Length] 

we would get an IndexOutOfRangeException

How does that method work exactly? In MSDN documentation it is clearly said, that startIndex is zero-based index of a string. Does it work and doesn't throw because a char array that String class operates on is null-terminated? I want to make sure that my program won't throw at any point.

like image 339
MindRoller Avatar asked Feb 04 '26 00:02

MindRoller


1 Answers

It's mentioned explicitly in the documentation:

Index numbering starts from 0. The startIndex parameter can range from 0 to the length of the string instance. If startIndex equals the length of the string instance, the method returns -1.

like image 72
Tim Schmelter Avatar answered Feb 05 '26 13:02

Tim Schmelter



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!