EN
C# / .NET - find text in string
0 points
In this article, we would like to show you how to find text in string in C# / .NET.
xxxxxxxxxx
1
string sampleString = "ABCD";
2
string text = "BC";
3
4
// returns true if string contains text
5
Boolean contains = sampleString.Contains(text);
6
Console.WriteLine(contains); // True
or
xxxxxxxxxx
1
string sampleString = "ABCD";
2
string text = "BC";
3
4
// returns index of the first occurrence of text in string
5
int index = sampleString.IndexOf(text);
6
Console.WriteLine(index); // 1
In this example, we use String.Contains()
method to check if the string
contains text
.
xxxxxxxxxx
1
using System;
2
3
public class StringUtils
4
{
5
public static void Main(string[] args)
6
{
7
string sampleString = "Dirask is awesome!";
8
string text = "is";
9
10
// returns true if string contains text
11
Boolean contains = sampleString.Contains(text);
12
Console.WriteLine("contains = " + contains); // contains = True
13
}
14
}
Output:
xxxxxxxxxx
1
contains = True
In this example, we use String.IndexOf()
method to find the index of the first occurrence of text
in the string
.
xxxxxxxxxx
1
using System;
2
3
public class StringUtils
4
{
5
public static void Main(string[] args)
6
{
7
string sampleString = "Dirask is awesome!";
8
string text = "is";
9
10
// returns index of the first occurrence of text in string
11
int index = sampleString.IndexOf(text);
12
Console.WriteLine("index = " + index); // 7
13
}
14
}
Output:
xxxxxxxxxx
1
index = 7