EN
C# / .NET - count character occurrences
0 points
In this article, we would like to show you how to count occurrences of a character in a String in C#.
Quick solution:
xxxxxxxxxx
1
char character = 'A';
2
string text = "ABAC";
3
4
int count = 0;
5
6
for (int i = 0; i < text.Length; ++i)
7
{
8
if (text[i] == character)
9
count += 1;
10
}
11
12
Console.WriteLine(count );
Output:
xxxxxxxxxx
1
2
In this example, we create simple for
loop to iterate through the string and check if each character matches the character
we want.
xxxxxxxxxx
1
using System;
2
3
public class Program
4
{
5
public static void Main()
6
{
7
char character = 'A';
8
string text = "ABAC";
9
10
int count = 0;
11
12
for (int i = 0; i < text.Length; ++i)
13
{
14
if (text[i] == character)
15
count += 1;
16
}
17
18
Console.WriteLine(count);
19
}
20
}
Output:
xxxxxxxxxx
1
2
In this example, to count character occurrences, we calculate the difference between the original string and the string with removed specified characters.
xxxxxxxxxx
1
using System;
2
3
public class TestClass
4
{
5
public static void Main()
6
{
7
string text = "ABCA";
8
string character = "A";
9
10
int result = text.Length - text.Replace(character, "").Length;
11
12
Console.WriteLine(result);
13
}
14
}
Output:
xxxxxxxxxx
1
2
In this example, we use Split()
method with string Length
to count the occurrences of the A
character in the text
.
xxxxxxxxxx
1
using System;
2
3
public class TestClass
4
{
5
public static void Main()
6
{
7
string text = "ABCA";
8
string character = "A";
9
int result = text.Split(character).Length - 1;
10
Console.WriteLine(result);
11
}
12
}
Output:
xxxxxxxxxx
1
2