2012-03-24

Code Patterns: IndexOf()

The IndexOf() String method in C# and VB.NET should be accompanied with an "if" statement as a matter of practice.  There are some exceptions, and the absence of the conditional should be explained in the comments around that code section.  Here are two examples demonstrating a code section using IndexOf() in C#:

    // IndexOf() with trinary conditional
    String strTest = "123456, 7890";
    int intCommaPosition = strTest.IndexOf(',');
    if (intCommaPosition > 0)
    {
        // stuff to do if the comma is found
    }
    else if (intCommaPosition == 0)
    {
        // stuff to do if the comma is the first char
        //  typically, this is an unusual condition
    }
    else
    {
        // stuff to do if the comma is not found
    }// of trinary if-else if on IndexOf() return value

    // IndexOf() with binary conditional
    intCommaPosition = strTest.TrimStart(',')

                          .TrimStart().IndexOf(',');
    if (intCommaPosition > -1)
    {
        // stuff to do if the comma is found
    }
    else
    {
        // stuff to do if the comma is not found
    }// of binary if on IndexOf() return value


The trinary can intercept the condition where the character leads the string.  The binary removes leading characters like the one we are looking for, then any leading whitespace, and finally it looks for the character of interest.  This way, the binary conditional's intCommaPosition calculation removes the unlikely instance that the string strTest starts with a comma.

This example uses C#, though VB.NET is similar.  Please remember to force the constants to characters if using Visual Basic.  Here's an example:

    Dim strTest As String = "123456, 7890"
    Dim intCommaPosition As Integer = 0

    ' uses variant 4 of 9 - IndexOf(String)
    intCommaPosition = strTest.IndexOf(",")
    ' uses variant 1 of 9 - IndexOf(Char) - faster
    intCommaPosition = strTest.IndexOf(","c)
    ' ... if statements! ...


As a programmer, I discovered this back in 1971, using InStr$() functions with Basic.  Even though those days had me coding in a high school closet using a 75 baud ball-and-hammer teletype through a 300 baud acoustic coupler into a telephone line that had a good deal of crosstalk as it traversed the city to the University of Pittsburgh, with persistent storage on paper-clipped paper tapes fashionably tucked into my dress shirt pocket, the code pattern remains: do not assume that the character will be found!

Sorry for the geek visual; it was a fun time in those days, and it still is fun now.
-- Steve