IndexOf method from string type tells us the index of a substring.
using System;
class Sample
{
public static void Main()
{
string s = "rntsoft.com";
Console.WriteLine(s.IndexOf("com"));
}
}
The output:
7
IndexOf returns -1 if not found.
using System;
class Sample
{
public static void Main()
{
string s = "rntsoft.com";
Console.WriteLine(s.IndexOf("C#"));
}
}
The output:
-1
We can perform the search from a starting point.
using System;
class Sample
{
public static void Main()
{
string s = "rntsoft.com";
Console.WriteLine(s.IndexOf("a", 2));
}
}
To seach in a case-insensitive manner, use the StringComparison enum.
using System;
class Sample
{
public static void Main()
{
Console.WriteLine("abcde".IndexOf("CD",
StringComparison.CurrentCultureIgnoreCase)); // 2
}
}
The output:
3
LastIndexOf works the same way as IndexOf, but is searches from the end of the string.
using System;
class Sample
{
public static void Main()
{
string s = "rntsoft.com";
Console.WriteLine(s.LastIndexOf("a"));
}
}
The output:
3