Dot Net Perls
C#

IndexOf Examples

by Sam Allen

Problem

Find the first occurence of a letter in a string. To do so, examine various ways of using IndexOf with loops on strings. This is to find the first occurrence of a letter or set of letters, and you may want to keep moving on and finding the following occurrences. Method must be reliable and fast.

Solution: C#

There are a few ways to use IndexOf. This isn't an article that simply lists function names, though, as we go in more in depth on some of them. But, let's start with a list of different methods and what they do, and then look at examples of the IndexOf loop.

Method name Its usage
IndexOf Used on string to find first index of parameter.
Returns -1 if not found.
IndexOfAny Finds first index of any of the char parameters.
Returns -1 if not found.

How can I use IndexOf in a loop?

By keeping track of several variables at once. Here we see the code for how you can loop through the instances of a char in a string. The syntax is a bit confusing for someone new to the language. The following code samples will help.

{
    string one = "I have a cat";
    // Loop through all instances of the letter 'a'.
    int increment = 0;
    while ((increment = one.IndexOf('a', increment)) != -1)
    {
        // Some code to get the string so far. You won't need these two lines
        // in your program.
        string thisString = one.Substring(increment);
        Console.WriteLine(thisString);
        // Very important to increment the int you are using in the loop.
        // You will definitely need this.
        increment++;
    }
}

What does IndexOf return?

IndexOf will return -1 when it doesn't find anything, and the index if it does. This is a bit more a C-like behavior than .NET, but it is efficient and fairly easy to use. I can't recall how many times I have caused IndexOutOfRangeException errors by trying to use the -1.

private void CheckString(string parameterValue)
{
    int indexFound = parameterValue.IndexOf("cat");
    if (indexFound == -1)
    {
        return;
    }
    else
    {
        // We now know for sure that the parameter contains "cat".
    }
}

How else can I use IndexOf?

You can use IndexOf quite elegantly with Substring. This demonstrates a practical use of getting the first substring that begins with a certain pattern or character. Note that the Substring method returns the rest of the string starting at specified number.

{
    string one = "I have a cat";

    // Starting at the first c, print out the remainder of the string.
    int first = one.IndexOf('c');
    string final = one.Substring(first);
    // This will print out the substring starting at the first index of c,
    // which will be 'cat'.
    Console.WriteLine(final);
}

How can I use IndexOfAny?

By providing a new char[] array. This is how you can use IndexOfAny when you need to test for multiple characters. Remember that using the built-in methods like this may be faster than doing all the calculations yourself, as native code in .NET can be optimized further.

{
    // Create a three-character char array. This is what we can
    // pass into IndexOfAny.
    char[] newArray = new char[]{ 'c', 'a', 't' };

    // Next, let's look at a sample of IndexOfAny.
    string one = "I have a cat";
    // Find first of any kind. Will result in "ve a cat".
    int firstAny = one.IndexOfAny(new char[] { 'v', 'e' });
    string finalAny = one.Substring(firstAny);
}

Conclusion

Use this code for when you need to loop over strings with IndexOf. This will perform well and accomplish many pattern-matching goals, without requiring the Split method or any of its problems. Finally, Finally, always remember check for -1 when using IndexOf.

© 2008 Sam Allen. All rights reserved.

Ads by The Lounge