Count the characters individually in a string using c#

落爺英雄遲暮 提交于 2021-02-08 12:15:44

问题


I have a string as follows:

string str = "ssmmmjjkkkkrrr"

Using C#, I need to display the count of each individual character as follows:

 s = 2
 m = 3
 j = 2
 k = 4
 r = 3

Thanks in advance.


回答1:


The simplest way would be to use LINQ:

var counted = text.GroupBy(c => c)
                  .Select(g => new { g.Key, Count = g.Count() });

foreach (var result in counted)
{
    Console.WriteLine("{0} = {1}", result.Key, result.Count);
}

Or even more briefly:

foreach (var group in text.GroupBy(c => c))
{
    Console.WriteLine("{0} = {1}", group.Key, result.Count());
}



回答2:


string str = "ssmmmjjkkkkrrr";
var counts = str.GroupBy(c => c).Select(g => new { Char = g.Key, Count = g.Count() });

foreach(var c in counts)
{
    Console.WriteLine("{0} = {1}", c.Char, c.Count);
}



回答3:


Since everyone has put linq solutions, I'll offer a simple code way to achieve the same result (probably much faster too)

 string str = "ssmmmjjkkkkrrr";
  Dictionary<char, int> counts = new Dictionary<char, int>();

  for (int i = 0; i < str.Length; i++)
       if (counts.ContainsKey(str[i]))
         counts[str[i]]++;
       else
         counts.Add(str[i], 1);

  foreach (var count in counts)
       Debug.WriteLine("{0} = {1}", count.Key, count.Value.ToString());

EDIT In response to the performance comment below I'll try to make this a little faster, this is dirty code but it runs pretty quickly.

The dictionary method will suffer from the way dictionaries allocate storage, each time you add an item that crosses the allocated storage threshold it doubles the storage available (allocate new array with the new size and copy over all elements), that takes some time! This solution gets around that.

// we know how many values can be in char.
int[] values = new int[char.MaxValue];

// do the counts.
for (int i = 0; i < text.Length; i++)
    values[text[i]]++;

// Display the results.
for (char i = char.MinValue; i < char.MaxValue; i++)
    if (values[i] > 0)
       Debug.WriteLine("{0} = {1}", i, values[i]);



回答4:


mystring.GroupBy(ch => ch)
        .Select(a => new { ch = a.Key, count = a.Count() })
        .ToList()
        .ForEach(x => Console.WriteLine("{0} = {1}", x.ch, x.count));


来源:https://stackoverflow.com/questions/10830228/count-the-characters-individually-in-a-string-using-c-sharp

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!