Scott Hanselman

The Daily Brain Fart - LastIndexOf broken? Oh, no, 'tis me.

November 20, 2004 Comment on this post [2] Posted in Learning .NET
Sponsored By

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!

public static void 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
}

About Scott

Scott Hanselman is a former professor, former Chief Architect in finance, now speaker, consultant, father, diabetic, and Microsoft employee. He is a failed stand-up comic, a cornrower, and a book author.

facebook twitter subscribe
About   Newsletter
Hosting By
Hosted in an Azure App Service
February 01, 2005 5:49
Good post, butnd ADD or copy coding gave the wrong comment for the last WriteLine.
March 26, 2005 18:49
Cassini is great for hosting the HttpRuntime in your own application (will this make Winforms history?) but I have discovered a serious problem with Cassini. It crashes with any sort of plugin on the page like Flash, etc. Does anyone know why??? - Pras, Toronto

Comments are closed.

Disclaimer: The opinions expressed herein are my own personal opinions and do not represent my employer's view in any way.