EN
C# / .NET - find character index in string
0 points
In this article, we would like to show you how to find a character index in string in C#.
Quick solution:
xxxxxxxxxx
1
String text = "ABC";
2
3
int result = text.IndexOf("A"); // 0
4
5
Console.WriteLine(result);
In this example, we use String.IndexOf()
method to find character index in the text
string.
xxxxxxxxxx
1
using System;
2
3
public class StringUtils
4
{
5
public static void Main(string[] args)
6
{
7
String text = "Dirask is awesome!";
8
9
int index1 = text.IndexOf("D"); // 0
10
int index2 = text.IndexOf("a"); // 3 (first occurrence)
11
12
int index3 = text.IndexOf("Dirask"); // 0
13
int index4 = text.IndexOf("is"); // 7
14
15
Console.WriteLine(index1); // 0
16
Console.WriteLine(index2); // 3 (first occurrence)
17
18
Console.WriteLine(index3); // 0
19
Console.WriteLine(index4); // 7
20
}
21
}
22
Output:
xxxxxxxxxx
1
0
2
3
3
0
4
7