C# String IndexOf() Method

htt‮www//:sp‬.theitroad.com

The IndexOf() method in C# is used to find the first occurrence of a specified character or substring within a string. It returns the zero-based index of the first occurrence of the specified character or substring, or -1 if the character or substring is not found.

The syntax of the IndexOf() method is as follows:

string.IndexOf(char value);

or

string.IndexOf(string value);

Here, string is the string to be searched, and value is the character or substring to be searched for.

If you use the first syntax, the IndexOf() method searches for the first occurrence of the specified character within the string. For example:

string str = "Hello, world!";
int index = str.IndexOf('o');
Console.WriteLine(index);  // Output: 4

In this example, the IndexOf() method is used to find the first occurrence of the character 'o' within the string "Hello, world!". The method returns the index 4, which is the zero-based index of the first occurrence of 'o'.

If you use the second syntax, the IndexOf() method searches for the first occurrence of the specified substring within the string. For example:

string str = "Hello, world!";
int index = str.IndexOf("world");
Console.WriteLine(index);  // Output: 7

In this example, the IndexOf() method is used to find the first occurrence of the substring "world" within the string "Hello, world!". The method returns the index 7, which is the zero-based index of the first occurrence of "world".

You can also use the IndexOf() method to search for a substring starting from a specified index within the string. To do this, you can use the following syntax:

string.IndexOf(string value, int startIndex);

Here, startIndex is the zero-based index from which to start the search. For example:

string str = "Hello, world!";
int index = str.IndexOf("o", 5);
Console.WriteLine(index);  // Output: 8

In this example, the IndexOf() method is used to find the first occurrence of the character 'o' within the string "Hello, world!", starting from the index 5. The method returns the index 8, which is the zero-based index of the first occurrence of 'o' after the fifth character.

Note that the IndexOf() method is case-sensitive by default. If you want to perform a case-insensitive search, you can use the following syntax:

string.IndexOf(string value, int startIndex, StringComparison comparisonType);

Here, comparisonType is a value of the StringComparison enumeration that specifies the type of comparison to perform (for example, StringComparison.OrdinalIgnoreCase for a case-insensitive comparison).