This post originated from an RSS feed registered with .NET Buzz
by Scott Hanselman.
Original Post: The Daily Brain Fart - LastIndexOf broken? Oh, no, 'tis me.
Feed Title: Scott Hanselman's ComputerZen.com
Feed URL: http://radio-weblogs.com/0106747/rss.xml
Feed Description: Scott Hanselman's ComputerZen.com is a .NET/WebServices/XML Weblog. I offer details of obscurities (internals of ASP.NET, WebServices, XML, etc) and best practices from real world scenarios.
Often, in the scope of writing massively scalable enterprise systems that manage your
finances, I parse strings. Mostly in my spare time.
What's happening here? I was reminded today that the start index passed to LastIndexOf()
was from the ass-end of the string. I then lamented the obviousness of this and was
then humbled by the silent-but-deadly odor my own brain fart.
I'm glad you're that much more confident in my abilities after reading this post.
Up with TDD! Down with ADD!
publicstaticvoid Main()
{ int newlineIndex = -1; string x ="bob\neric\nfred\nted"; string z ="bob\r\neric\r\nfred\r\nted";
newlineIndex = x.LastIndexOf('\n',0);
Console.WriteLine(newlineIndex); //Expect
13, always get -1
newlineIndex = z.LastIndexOf('\n',0);
Console.WriteLine(newlineIndex); //Expect
16, always get -1
newlineIndex = x.LastIndexOf('\n');
Console.WriteLine(newlineIndex); //Expect
13, get 13
newlineIndex = z.LastIndexOf('\n');
Console.WriteLine(newlineIndex); //Expect
16, get 16
//Fart
realized...
newlineIndex = x.LastIndexOf('\n',x.Length-1);
Console.WriteLine(newlineIndex); //Expect
13, always get 13
newlineIndex = z.LastIndexOf('\n',z.Length-1);
Console.WriteLine(newlineIndex); //Expect
13, always get 13
}