15,032,967 members
See more:
So i already have a code which counts how many occurances there are of a letter in string. Now i don't know how to make so that it counts a symbol(like how many "!" there are). I have a string with alphabet and one custom letter "Ą", so i need to know how do i use those letters from "R"("string R = "..." ) to count occurances of a letter in the console. I heard the best way is to use indexof() but i have no clue on how to use it?
```using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Collections;
using System.IO;

namespace _5._1
{
class LetterOccur
{
private const int CMax = 256;
private int[] Rn;
public string eil { get; set; }
public string R = "AĄBCDEFGHIJKLMNOPRSTUVQZW";
public LetterOccur()
{
eil = "";
Rn = new int[CMax];
for (int i = 0; i < CMax; i++)
{
Rn[i] = 0;
}
}
public int Take(char sim)
{
return Rn[sim];
}

public void many()
{
for (int i = 0; i < eil.Length; i++)
{
if (('A' <= eil[i] && eil[i] <= 'Z')||(('a' <= eil[i] && eil[i] <= 'z')))
{
Rn[eil[i++]]++;
}
}
}
}
class Program
{
const string CFr = "..\\..\\Rezults.txt";
static void Main(string[] args)
{
LetterOccur eil = new LetterOccur();
string R = "AĄBCDEFGHIJKLMNOPRSTUVQZW";
Console.WriteLine("Enter a line of words: ");
eil.eil = line;
eil.many();
print(CFr, eil, R);
}
static void print(string fv, LetterOccur eil, string R)
{
using (var fr = File.CreateText(fv))
{
for (char sim = 'a'; sim <= 'z'; sim++)
{
fr.WriteLine("{0, 3:c} {1, 4:d} |{2, 3:c} {3, 4:d}",
sim, eil.Take(sim),
Char.ToUpper(sim), eil.Take(Char.ToUpper(sim)));
}
}
}
}
}```

What I have tried:

Dont know how to count custom characters in C#
Posted
Updated 17-Nov-18 4:10am
v2

## Solution 1

Hi,

string your_string = "abc!defgh!jkl";
C#
```//Solution 1 - remove the character and subtract the length.
int result1 = your_string.Length - your_string.Replace("!", "").Length;

//Solution 2 - split the string into an array by using your target character as a delimiter
int result2 = your_string.Split('!').Length - 1;

//Solution 3 - use the LINQ
int result3 = your_string.ToCharArray().Count(c => c == '!');```

Cheers,
AH
v2
Richard Deeming 20-Nov-18 11:48am

You can make solution 3 even simpler by removing the `.ToCharArray()` call. :)

## Solution 2

Have a look at this: Counting Lines in a String[^] it's based on lines (so there are some bits you can ignore) but newline is just a character in a text file, so most oif the methods it shows will work for any character.

To find out how many of each character there are in your string in one line, this will work:
```string input = "ABCDABDFGHI";
Dictionary<char, int> counts = input.GroupBy(x => x).ToDictionary(x => x.Key, x => x.Count());
```
Each element of the dictionary will be the character and how many times it appears.