String.LastIndexOf(…) subtleties

July 11th, 2009

I was trying to use the String.LastIndexOf (String searchTerm, Int32 startIndex, Int32 count) method, and kept getting and ArgumentOutOfRangeException that made no sense to me. Even though I was 100% sure I was feeding it a valid count (the number of characters to search, starting at the startIndex), it would complain. Finally I called the method using startIndex = 0 and count = myString.Length, but I STILL got the same exception!

So I googled. And whaddayaknow, I WAS doing it wrong! See, I thought the method searched the string in a left-to-right manner, but it doesn’t - it searches from the back of the string forward. So the startIndex should be the last character to start from, and the count should be how many characters forward from that point to search…

Now who’s stupid: me or Microsoft? Actually, don’t answer that. :-)

Code | Comments | Trackback Jump to the top of this page

Leave a Reply

You must be logged in to post a comment.

potentially harmless, probably useless

Meta