simple solution for characters frequency in string object

后端 未结 4 1093
感情败类
感情败类 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:24

    You can easily do it using Linq like:

     string sign = "attitude";
     int count = sign.Count(x=> x== 'a');
    

    or if you want all characters count then:

     string sign = "attitude";
     var alphabetsCount = sign.GroupBy(x=> x)
                              .Select(x=>new 
                                        {
                                          Character = x.Key, 
                                          Count = x.Count()
                                        });
    

    Here is a working Example

    UPDATE:

    Without Linq you can do it with a loop and track it in a dictionary like:

    string sign = "attitude";
    Dictionary dic = new Dictionary();
    foreach(var alphabet in sign)
    {
        if(dic.ContainsKey(alphabet))
            dic[alphabet] = dic[alphabet] +1;
        else
            dic.Add(alphabet,1);
    }
    

    Here is Demo without Linq using Dictionary<>

提交回复
热议问题