simple solution for characters frequency in string object

后端 未结 4 1001
感情败类
感情败类 2021-01-27 03:13

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 h

4条回答
  •  迷失自我
    2021-01-27 03:39

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

    var characterCount= new Dictionary();
    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);
    }
    

提交回复
热议问题