In C#, IndexOf() searches a string from left to right and returns the position of the first match. Positions start at 0, so the first character is index 0. When nothing matches, it returns -1.
You can search for a single char or for a whole string. You can also tell it where to start (startIndex) and how many characters to look at (count). Use it when you need to know where something is, for example to cut the text with Substring(). If you only need yes or no, Contains() is simpler.
This is an instance member of System.String. Call it on a string variable, such as text.IndexOf(...). Calling it on a null variable throws NullReferenceException. It only reads the text. Strings are immutable, so the original string is never changed.
Syntax
Call IndexOf on the string you search in. Pass what you are looking for.
C#
string text = "banana";
int a = text.IndexOf('n'); // 2
int b = text.IndexOf("na", StringComparison.Ordinal); // 2
int c = text.IndexOf('n', 3); // 4 (start looking at index 3)
int d = text.IndexOf('x'); // -1 (not found)
Call
What it does
text.IndexOf('a')
Position of the first 'a'. A char search is always ordinal (exact code match).
text.IndexOf("na", StringComparison.Ordinal)
Position of the first "na", comparing exact character codes. Recommended for string searches.
text.IndexOf('a', 2)
Start the search at index 2 and look to the end.
text.IndexOf('a', 2, 3)
Look only at 3 characters, starting at index 2.
The plain IndexOf(string) overload uses the current culture, so it can give surprising results. For example, on .NET 5 and later, "a\r\nb".IndexOf("\n") can return -1 because the culture rules treat \r\n as one unit. Pass StringComparison.Ordinal for safe, predictable results. Searching for an empty string "" returns 0.
Library declarations
C#
public int IndexOf(char value);
public int IndexOf(char value, int startIndex);
public int IndexOf(char value, int startIndex, int count);
public int IndexOf(char value, StringComparison comparisonType); // newer .NET
public int IndexOf(string value);
public int IndexOf(string value, int startIndex);
public int IndexOf(string value, int startIndex, int count);
public int IndexOf(string value, StringComparison comparisonType);
public int IndexOf(string value, int startIndex, StringComparison comparisonType);
public int IndexOf(string value, int startIndex, int count, StringComparison comparisonType);
Parameters
Parameter
Description
value
Required. The char or string to find. A null string throws ArgumentNullException.
startIndex
Optional. Where the search begins. Must be from 0 to Length, or you get ArgumentOutOfRangeException.
count
Optional. How many characters to examine, starting at startIndex.
comparisonType
Optional. A StringComparison value such as Ordinal or OrdinalIgnoreCase.
Return Value
Return Value
Description
0 or more
The zero-based index where the first match starts.
-1
No match was found.
C# Examples
Example 1 — Find a Character and a Word
Look for one letter, one word, and something that is not there at all.
C#
using System;
class Program {
static void Main() {
string text = "banana split";
Console.WriteLine(text.IndexOf('a'));
Console.WriteLine(text.IndexOf("split", StringComparison.Ordinal));
Console.WriteLine(text.IndexOf('z'));
}
}
Output
1
7
-1
How It Works
Counting starts at zero.b is index 0, so the first 'a' sits at index 1. IndexOf stops at the first hit and ignores the other as.
A word search reports where the word begins."banana" takes indexes 0 to 5 and the space is 6, so "split" starts at 7.
Missing means -1. There is no 'z', so the call returns -1 instead of throwing. Test for that value before using the number.
The text is untouched. Searching never edits text; it still holds banana split after all three calls.
Example 2 — Find Every Match with startIndex
Loop through the string and report every 'a' by starting each new search just after the last hit.
C#
using System;
class Program {
static void Main() {
string text = "banana";
int pos = text.IndexOf('a');
while (pos != -1) {
Console.WriteLine("Found 'a' at " + pos);
pos = text.IndexOf('a', pos + 1);
}
}
}
Output
Found 'a' at 1
Found 'a' at 3
Found 'a' at 5
How It Works
First search. Without a start position the search begins at index 0 and finds the 'a' at 1.
Move past the hit.pos + 1 tells the next call to begin one character later, so the same 'a' is not found again and again.
The loop ends by itself. After index 5 the next start is 6, which equals Length. That is allowed, and the call returns -1, so the while test fails.
Positions stay absolute. Even with a start position, each result counts from the beginning of the word: 1, 3, and 5.
Example 3 — Use the Index to Cut an Email Address
Find the @, cut the user name and the domain around it, then compare a case-sensitive and a case-insensitive search.
C#
using System;
class Program {
static void Main() {
string email = "[email protected]";
int at = email.IndexOf('@');
string user = email.Substring(0, at);
string domain = email.Substring(at + 1);
Console.WriteLine(user);
Console.WriteLine(domain);
Console.WriteLine(email.IndexOf("example", StringComparison.Ordinal));
Console.WriteLine(email.IndexOf("example", StringComparison.OrdinalIgnoreCase));
}
}
Output
Sam.Lee
Example.com
-1
8
How It Works
Locate the separator.Sam.Lee uses indexes 0 to 6, so at is 7.
Cut around it.Substring(0, at) takes 7 characters for the user name, and Substring(at + 1) takes everything after the @.
Exact match fails. The address has a capital E, so an ordinal search for lowercase example returns -1.
Ignore case finds it.OrdinalIgnoreCase treats E and e as equal and reports index 8, right after the @.
Frequently Asked Questions
It returns the zero-based position where the first match starts. If the character or substring is not in the string, it returns -1. It never throws just because nothing was found.
Because the value was not found, or because of case and culture rules. IndexOf is case-sensitive, so "Cat".IndexOf("cat", StringComparison.Ordinal) is -1. Pass StringComparison.OrdinalIgnoreCase to ignore case.
Yes, for string arguments. The plain IndexOf(string) overload uses the current culture, which can give different answers on different machines. Ordinal compares exact character codes, which is fast and predictable. The char overload is already ordinal.
Search once, then call IndexOf again with startIndex set to the last position plus one. Repeat until it returns -1. Example 2 on this page shows the full loop.
Contains only answers yes or no. IndexOf tells you where the match starts, which you need for Substring, Remove, or Insert. text.Contains(x) gives the same yes or no as text.IndexOf(x) >= 0 when both use the same comparison rules.