Click here to Skip to main content
15,885,757 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
Hi,

I want to write a program which is able to count the ocurence of character.

Example:
input string=NAMAN
Output will be:
N=2
A=2
M=1

Regards
Posted
Comments
[no name] 9-May-13 9:48am    
Okay thanks for letting us know. Good luck with that.

Look here:
C#
var chars = "NAMAN";
chars.Distinct().ToList().ForEach(c => Console.WriteLine("{0}={1}", c, chars.Count(i => i == c)));


[update: ToCharArray() is not needed]
 
Share this answer
 
v2
Comments
ridoy 9-May-13 13:04pm    
absolutely fantastic,clear and short,my 5!
Zoltán Zörgő 9-May-13 15:33pm    
Thank you.
Zoltán Zörgő 9-May-13 15:43pm    
I would be really interested why I got the downvote :(
ridoy 9-May-13 15:48pm    
It may be that old thing of CP,someone find vote 1 is the highest among 5 votes!!..:D
Zoltán Zörgő 10-May-13 3:15am    
Might be :)
I have a significant improvement using LINQ from solution 3:

C#
str.ToCharArray().GroupBy(i => i).OrderBy(k => k.Key).ToList().
  ForEach(m => Console.WriteLine(string.Format("{0}: {1}", m.Key, m.Count())));
 
Share this answer
 
v3
Sniff, sniff... Yep, smells like homework!

Sorry, but the answers you got will probably get you a failing grade in your class. With the level of the assignment you got, there's no way your class covered the methods demonstrated in the answers you got here and the person teaching the class will KNOW you didn't write the code.
 
Share this answer
 
Comments
Richard C Bishop 9-May-13 12:19pm    
Time will tell, but you are correct.
Dave Kreskowiak 9-May-13 12:55pm    
Yeah, but, we'll never know what happens beyond what's posted here.

But, I especially love the 1-vote I got! The truth is sometimes painful for other to hear.
Richard C Bishop 9-May-13 13:37pm    
So true, if the truth comprimises one's status quo, then it is simply ignored or even ridiculed. +5 to even the odds ;)
C#
string charapp = "NAMAN";
string data = charapp.Distinct().Select(m => new { Key = m, Val = charapp.Count(x=> x.Equals(m)).ToString() }).
Select(m=> m.Key + ":" + m.Val).Aggregate((a,b)=> a + "\n" + b);

Debug.Write(data);
 
Share this answer
 
v2
C#
int count = inputstring.Count(f => f == 'N');

If you don't want to use LINQ you can use below
C#
int count = inputstring.Split('N').Length - 1;
 
Share this answer
 
v2
Comments
Orcun Iyigun 9-May-13 10:08am    
So he should write this code for each character starting from A to Z ??

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