The String IndexOf() method returns the index of the first occurrence of the specified character/substring within the string.
Example
using System;
namespace CsharpString {
class Test {
public static void Main(string [] args) {
string str = "Ice cream";
// returns index of substring cream
int result = str.IndexOf("cream");
Console.WriteLine(result);
Console.ReadLine();
}
}
}
// Output: 4
IndexOf() Syntax
The syntax of the string IndexOf() method is:
String.IndexOf(string value, int startindex, int count)
Here, IndexOf() is a method of class String.
IndexOf() Parameters
The IndexOf() method takes the following parameters:
- value - string to search
- startIndex - starting position of the search
- count - number of character positions to examine
IndexOf() Return Value
The IndexOf() method returns:
- index of the first occurrence of the specified character/string
- -1 if the specified character/string is not found
Example 1: C# String IndexOf()
using System;
namespace CsharpString {
class Test {
public static void Main(string [] args) {
string str = "Ice cream";
int result;
// returns index of character 'I'
result = str.IndexOf('I');
Console.WriteLine("Index of I: " + result);
// returns -1
result = str.IndexOf('P');
Console.WriteLine("Index of P: " + result);
Console.ReadLine( );
}
}
}
Output
Index of I: 0 Index of P: -1
Here,
str.IndexOf('I')- returns0as'I'is in index 0 of strstr.IndexOf('P')- returns-1as'P'is not in str
Example 2: IndexOf() With Start Index
using System;
namespace CsharpString {
class Test {
public static void Main(string [] args) {
string str = "Ice cream";
int result;
// returns index of char I
result = str.IndexOf('I', 0);
Console.WriteLine("Index of I: " + result);
// returns -1
result = str.IndexOf('I', 2);
Console.WriteLine("Index of I: " + result);
Console.ReadLine( );
}
}
}
Output
Index of I: 0 Index of I: -1
In this program,
str.IndexOf('I', 0)- starts the search from index 0str.IndexOf('I', 2)- starts the search from index 2
As we can see, str.IndexOf('I', 2) returns -1 since 'I' cannot be found after index 2.
Example 3: IndexOf() With Start Index And Count
using System;
namespace CsharpString {
class Test {
public static void Main(string [] args) {
string str = "Ice cream";
int result;
// returns -1
result = str.IndexOf('m', 0, 1);
Console.WriteLine("Index of m: " + result);
// returns index of m
result = str.IndexOf('m', 0, 9);
Console.WriteLine("Index of m: " + result);
Console.ReadLine( );
}
}
}
Output
Index of m: -1 Index of m: 8
Here,
str.IndexOf('m', 0, 1)- performs search in 1 character from index 0str.IndexOf('m', 0, 9)- performs search in 9 characters from index 0
As we can see, str.IndexOf('m', 0, 1) returns -1 since 'm' cannot be found within 1 character after index 0.