
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. By reviewing these examples, we learn ways to use the IndexOf method on the string type in loops, and some tips and samples.
First, here we note that there are four IndexOf instance methods. 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:
This method finds the first index of the char argument.
It returns -1 if the char was not found.
IndexOfAny:
This method finds the first index of any of the char arguments.
It returns -1 if none are found.
LastIndexOf:
This finds the last index of the char argument.
It returns -1 if the char was not found.
LastIndexOfAny:
This finds the first index of any of the char arguments.
It returns -1 if none are found.
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".
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
string contains 'Vader'Description. 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.
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.
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
ave a cat
a cat
atDescription. 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.
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.

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. I have caused an IndexOutOfRangeException by using the -1 in other code. This is different than the result from the Contains method. See below for information on the Contains method.
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.
Substring ProgramsProgram that uses Substring [C#]
using System;
class Program
{
static void Main()
{
// Input.
const string s = "I have a cat";
// Location of the letter c.
int i = s.IndexOf('c');
// Remainder of string starting at 'c'.
string d = s.Substring(i);
Console.WriteLine(d);
Console.ReadLine();
}
}
Output
catHere 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.
IndexOfAny String Method
Here we test the IndexOf method against a single character iteration for-loop. I wanted to know if scanning through a string with a single char loop was faster than using IndexOf over each character. I 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.
Char version [C#]
int c = 0;
for (int e = 0; e < s.Length; e++)
{
if (s[e] == '.')
{
c++;
}
}
IndexOf version [C#]
int c = 0;
int e = 0;
while ((e = s.IndexOf('.', e)) != -1)
{
e++;
c++;
}
Results
Char version: 1545 ms
IndexOf version: 2215 msYou 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.
LastIndexOf String MethodYou can replace character iteration loops completely replaced with IndexOf in some situations. This can result in much clearer code. The second code example may clearer for some developers.
For loop version [C#]
int number = -1;
for (int y = 0; y < value.Length; y++)
{
if (value[y] == '1')
{
number = y;
break;
}
}
IndexOf version [C#]
int number = value.IndexOf('1');Benchmark. Because I had nothing better to do, I executed these two pieces of code and tested their performance in tight loops. The imperative for-loop was faster by a couple nanoseconds. If you are desperate for performance, this can help.
Results
Test string literal is "something-1-two".
For loop: 11.19 ns
IndexOf: 14.01 ns
Here you want to know if there is a difference between calling IndexOf with a single character string argument, and with a char argument. 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 [C#]
int i = s.IndexOf("a");
// Finds first "a" string in s.
IndexOf usage with char [C#]
int i = s.IndexOf('a');
// Finds first 'a' char in s.
Results
Ten million tests.
String version: 1154 ms
Char version: 172 msInterpretation. What I 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.
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.
Contains String Method
In this article, 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.
String Type