C# IndexOf String Examples

by Sam Allen - Updated January 7, 2010

You want to find the first occurrence of a letter in your string with the IndexOf method in the .NET Framework using the C# programming language. Find letters in loops or simply the first or last occurrence. Here we look at ways to use the IndexOf method on the string type in loops, and some tips and samples, using the C# programming language.

Using IndexOf methods

First, here we note that there are four IndexOf instance methods here. The first two methods find the first indexes. They scan through the characters from the left to right. The second two find the last indexes, and they go from right to left.

 IndexOf 
    Finds first index of char.
    Returns -1 if not found.
    [MSDN source]

 IndexOfAny 
    Finds first index of any of the chars.
    Returns -1 if none are found.
    [MSDN source]

 LastIndexOf 
    Finds last index of char.
    [MSDN source]

 LastIndexOfAny 
    Finds last index of any in char group.
    [MSDN source]

Using IndexOf to test strings

In this example, we use IndexOf simply to see whether the input string contains a string. We want to see if the string in the example contains "Vader".

=== Example program that uses IndexOf (C#) ===

using System;

class Program
{
    static void Main()
    {
        // A.
        // The input string.
        const string s = "Darth Vader is really scary.";

        // B.
        // Test with IndexOf.
        if (s.IndexOf("Vader") != -1)
        {
            Console.Write("string contains 'Vader'");
        }
        Console.ReadLine();
    }
}

=== Output of the program ===

string contains 'Vader'

Description of the example. In part A, it has an input string. This string is what we want to test. In part B, it calls IndexOf. IndexOf returns the location of the string 'Vader'. It is not equal to -1, so the line is written to the console window.

Using IndexOf in loops

Here we see how you can use the IndexOf instance method in loops. To do this, keep track of several values at once. You can loop through the instances of a char in a string. Here we loop over each 'a' in the string.

=== Example program that uses IndexOf in loop (C#) ===

using System;

class Program
{
    static void Main()
    {
        // A.
        // The input string.
        string s = "I have a cat";

        // B.
        // Loop through all instances of the letter a.
        int i = 0;
        while ((i = s.IndexOf('a', i)) != -1)
        {
            // C.
            // Print out the substring for demo.
            Console.WriteLine(s.Substring(i));

            // D.
            // Increment the index.
            i++;
        }
        Console.ReadLine();
    }
}

=== Output of the program ===

ave a cat
a cat
at

Description of IndexOf looping. In part A, it has an input string. This string is what we are testing with IndexOf. In part B, it uses a while loop. The while loop is the best way to do this. We test it for success each time. If the character isn't found, the loop will end.

Description of loop contents. In part C, it writes the result to the console. You don't need this part but it writes the Substring starting at the variable i to the end of the string. In part D, the index is incremented. We must advance past the current character by adding one to the index. If you don't do this, you will get an infinite loop.

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. The author has caused IndexOutOfRangeException by using the -1. This is different than the result from the Contains method. See below for information on the Contains method.

Using IndexOf with Substring

Here we see that you can use the IndexOf method with the Substring method. Here we get the first substring that begins with a certain pattern or character. The Substring method returns the rest of the string starting at your specified number.

(See Substring Programs.)

=== Example program that uses Substring (C#) ===

using System;

class Program
{
    static void Main()
    {
        // A.
        // Input.
        const string s = "I have a cat";

        // B.
        // Location of the letter c.
        int i = s.IndexOf('c');

        // C.
        // Remainder of string starting at 'c'.
        string d = s.Substring(i);
        Console.WriteLine(d);
        Console.ReadLine();
    }
}

=== Output of the program ===

cat

Understanding IndexOfAny

Here we note that the .NET Framework provides an IndexOfAny method on the string type in the C# programming language. You can use this method to search for the first index of any of the characters provided in the char[] array parameter. This method is the same as calling the IndexOf method several times with the logical OR operator, but has different performance characteristics and is simpler.

(See IndexOfAny String Method.)

Benchmark

Here we test the IndexOf method against a single character iteration for loop. The author wanted to know if scanning through a string with a single char loop was faster than using IndexOf over each character. The results are noted after the example.

=== Char version ===

int c = 0;
for (int e = 0; e < s.Length; e++)
{
    if (s[e] == '.')
    {
        c++;
    }
}

=== IndexOf version ===

int c = 0;
int e = 0;
while ((e = s.IndexOf('.', e)) != -1)
{
    e++;
    c++;
}

=== Benchmark result ===

Char version:    1545 ms
IndexOf version: 2215 ms

Result of the benchmark. The author found that it is more efficient to scan each character individually than to use IndexOf. This may be because using IndexOf is more complex and therefore harder to optimize for the compiler.

What about LastIndexOf?

You can use LastIndexOf to search the source string just like IndexOf. The LastIndexOf and LastIndexOfAny methods work the same way but in reverse. They still return -1 if the char cannot be found. These are used much less frequently. You can find more information on the LastIndexOf method on the string type on a separate page on this site.

(See LastIndexOf String Method.)

Replacing your loop with IndexOf

Here we see how you can replace character iteration loops. Loops can be completely replaced with IndexOf in some situations. This can result in much clearer code. The following two pieces of code should perform about the same but the second is clearer for some developers.

=== For loop ===

int i = -1;
for (int y = 0; y < s.Length; y++)
{
    if (c == 'a')
    {
        i = y;
        break;
    }
}

=== Same loop with IndexOf ===

int i = s.IndexOf('a');

IndexOf with char vs. IndexOf with string

Here you want to know if there is a difference between calling IndexOf with a single character string parameter, and with a char parameter. If you call IndexOf with a string, globalization rules will be applied. Therefore, the string IndexOf will utilize more CPU cycles. However, even if you pass in StringComparison.Ordinal, it is slower.

=== IndexOf usage with string ===

int i = s.IndexOf("a");
// Finds first "a" string in s.

=== IndexOf usage with char ===

int i = s.IndexOf('a');
// Finds first 'a' char in s.

=== Benchmark result (ten million tests) ===

Char version:    1154 ms
IndexOf version: 172 ms

Interpretation of the results. What the tester found here is that calling IndexOf with a string is nearly ten times slower than calling it with a character. This is the case even with a single-character string.

Contains and IndexOf

The Contains method is a wrapper method that calls IndexOf with StringComparison.Ordinal. This means it has two major differences to remember. The first difference is that it returns true or false, not an integer. If its internal IndexOf returns -1, it returns false, otherwise it returns true.

(See Contains String Method.)

Summary

Here we saw several examples of using IndexOf, using the C# programming language. You will commonly use IndexOf to search for substrings in your strings; there is no method called Search, but the general idea is performed by IndexOf. These are powerful methods and are used in many programs with success.

(Do not copy this page.)

Dot Net Perls | Search
Strings | Environment.NewLine | List and String Conversion | Replace String Examples | Split String Examples | Substring Programs
C# | Decrement Int | HTML Brackets | Parameter Optimization Tip | SaveFileDialog Tutorial
© 2010 Sam Allen. All rights reserved.
Dot Net Perls | Sam Allen