Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
538 views
in Technique[技术] by (71.8m points)

c# - simple solution for characters frequency in string object

The task what I'm trying to do is about showing up the frequency of every single characters from the string object, for the moment I've done some part of code, just doesn't have the easy concept in my mind for finishing this task. So far I was thinking that it might be usefull to changing the char into int type. What is worth mentioning I'd like to avoid using the part: if (letter == 'a') NumberCount++; as if it wouldnt be efficient to write that much conditions for that simple task, and I'was thinking of doing it way mentioned above. I'd be gratefull for any sugestions of how to code it further.....I'm beginner at c#

 class Program
 {
    static void Main(string[] args)
    {
       string sign = "attitude";
       for (int i = 0; i < sign.Length; i++)
       {
          int number = sign[i]; // changing char into int

       } 
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Here's a non Linq way to get the counts of all the unique letters.

var characterCount= new Dictionary<char,int>();
foreach(var c in sign)
{
    if(characterCount.ContainsKey(c))
        characterCount[c]++;
    else
        characterCount[c] = 1;
}

Then to find out how many "a"s there are

int aCount = 0;
characterCount.TryGetValue('a', out aCount);

Or to get all the counts

foreach(var pair in characterCount)
{
    Console.WriteLine("{0} - {1}", pair.Key, pair.Value);
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...