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.
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]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.
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
atDescription 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.
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.
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.
=== 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 ===
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.
(See IndexOfAny String Method.)
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 msResult 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.
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.)
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');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 msInterpretation 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.
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.
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.