Click here to Skip to main content
15,889,216 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I'm a beginner in c# and have a question ,
how do i count the occurrence of each single character of a text with the ascii code

What I have tried:

Console.WriteLine("text: ");
txt = Console.ReadLine()
Posted
Updated 28-May-18 20:34pm

C# doesn't use ASCII by default - it uses Unicode which is wider (16 bit instead of 7 or 8 for Extended ASCII) . when you use Console.readLine the string you get is a Unicode string, containing Unicode chars. For "true ASCII" you would have to use an array of bytes, and translate the Unicode:
string s = Console.ReadLine();
byte[] bytes = System.Text.Encoding.ASCII.GetBytes(s);


But ... for most input that's irrelevant, and if you're a beginner this is probably your homework to count characters.
Easiest way? Sort them. Then the repetitions are all next to each other and you can count them with a simple loop:
1) Set count to zero.
2) Set currentChar to '\0'
3) Loop through each character in the sorted data
3.1) Is currentChar is the same as the loop character?
3.1.1) Yes: increment count
3.1.2) No: Is currentChar '\0'?
3.1.2.1) Yes: increment count, set currentChar to loop character
3.1.2.2) No: Print currentChar and count, set count to 1, set currentChar to loop char
4) After loop, print currentChar and count
 
Share this answer
 

You could always use Linq. Convert the string to a List of type char. Sort the List. Group the characters by character into a new anonymous type with two fields, Letter and Count. Letter is the group key and Count is the total count of group items. Enumerate the query and print the results to the console.

 
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