Click here to Skip to main content
15,899,935 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I m writing a sample programs WPF which will read a text.txt file with openfiledialouge and will show result occurrence of each character including special characters(~!@#$%^&*()_+-) in textbox.
what i wrote is write all content of file to textbox.
I want to count occurrence of each character and output in textbox.

Sample output:
<pre><pre>Number of 'a':10
Number of 'b':20
Number of '@':5

.
.
Number of 'z':15


What I have tried:

protected void Button_Click(object sender, RoutedEventArgs e)
{
    OpenFileDialog openFile = new OpenFileDialog();

    if (openFile.ShowDialog()==true)
    {
        string filepath = openFile.FileName;
        textbox.Text = File.ReadAllText(filepath);


        readbar.Value = 100;

    }

}
Posted
Updated 28-Jan-18 2:04am
v4

You could use a Dictionary<char, int> to count each character's occurrences.
C#
Dictionary<char, int> occurrences = new Dictionary<char, int>();
string text = File.ReadAllText(filepath);
foreach (char c in text) {
   if (!occurrences.ContainsKey(c)) {
      occurrences.Add(c, 1);
   }
   else {
      occurrences[c]++;
   }
}

You will end with the number of occurrences of each character in the string. But it may get a little more difficult if your input text file contains unicode characters which cannot be represented by a simple char value.
 
Share this answer
 
Comments
Ĥãsŋäḭn Ɏḁɋoȱb 30-Jan-18 12:19pm    
what would be the code , if we want to count only special character .?
Try this:
C#
string content = "ABCDEFFGGGHHHHIIIII";
var differentChars = content.GroupBy(g => g).Select (g => new {c = (char) g.Key, count = g.Count()});
You can then use foreach
C#
foreach (var pair in differentChars)
    {
    Console.WriteLine("{0}:{1}", pair.c, pair.count);
    }
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900