String Search for Index
In this chapter you will learn:
- Search with IndexOf
- String from the middle
- String by case
- Search a character from the last with LastIndexOf
- Index of any characters
- Search a character in a string
Search with IndexOf
IndexOf
method from string type tells us
the index of a substring.
using System;// ja v a 2 s . c o m
class Sample
{
public static void Main()
{
string s = "java2s.com";
Console.WriteLine(s.IndexOf("com"));
}
}
The output:
IndexOf returns -1 if not found.
using System;/* j a va 2s . c o m*/
class Sample
{
public static void Main()
{
string s = "java2s.com";
Console.WriteLine(s.IndexOf("C#"));
}
}
The output:
String from the middle
We can perform the search from a starting point.
using System;//from j ava2 s .c om
class Sample
{
public static void Main()
{
string s = "java2s.com";
Console.WriteLine(s.IndexOf("a", 2));
}
}
String by case
To seach in a case-insensitive manner,
use the StringComparison
enum.
using System;// ja v a 2 s . c o m
class Sample
{
public static void Main()
{
Console.WriteLine("abcde".IndexOf("CD",
StringComparison.CurrentCultureIgnoreCase)); // 2
}
}
The output:
Search a character from the last with LastIndexOf
LastIndexOf
works the same way as
IndexOf
, but is searches from the end of the string.
using System;/*from j ava 2 s. c om*/
class Sample
{
public static void Main()
{
string s = "java2s.com";
Console.WriteLine(s.LastIndexOf("a"));
}
}
The output:
Index of any characters
IndexOfAny
returns the index of any characters specified.
using System;//from j a va 2 s. c o m
class Sample
{
public static void Main()
{
string s = "java2s.com";
Console.WriteLine(s.IndexOfAny(new char[] { 'a', 'v' }));
}
}
The output:
Search a character in a string
using System; //from j a v a 2s .c o m
class MainClass {
public static void Main() {
string str = "abcdefghijk";
int idx;
Console.WriteLine("str: " + str);
idx = str.IndexOf('h');
Console.WriteLine("Index of first 'h': " + idx);
}
}
The code above generates the following result.
using System; /*from jav a 2 s .co m*/
class MainClass {
public static void Main() {
string str = "abcdefghijk";
int idx;
idx = str.IndexOf("def");
Console.WriteLine("Index of first \"def\": " + idx);
}
}
The code above generates the following result.
Next chapter...
What you will learn in the next chapter:
Home » C# Tutorial » String