使用 c# 单独计算字符串中的字符数

本文关键字:字符 字符串 单独 计算 使用 | 更新日期: 2023-09-27 18:35:46

我有一个字符串如下:

string str = "ssmmmjjkkkkrrr"

使用 C#,我需要显示每个字符的计数,如下所示:

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

提前谢谢。

使用 c# 单独计算字符串中的字符数

最简单的方法是使用 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);
}

或者更简短地说:

foreach (var group in text.GroupBy(c => c))
{
    Console.WriteLine("{0} = {1}", group.Key, result.Count());
}
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);
}

由于每个人都使用了 linq 解决方案,我将提供一种简单的代码方法来获得相同的结果(可能也快得多)

 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());

编辑为了响应下面的性能评论,我将尝试使其更快一点,这是脏代码,但它运行得很快。

字典

方法将受到字典分配存储方式的影响,每次添加超过分配存储阈值的项目时,它都会使可用存储空间加倍(使用新大小分配新数组并复制所有元素),这需要一些时间!这个解决方案可以解决这个问题。

// 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]);
mystring.GroupBy(ch => ch)
        .Select(a => new { ch = a.Key, count = a.Count() })
        .ToList()
        .ForEach(x => Console.WriteLine("{0} = {1}", x.ch, x.count));
string str = "ssmmmjjkkkkrrr";
Dictionary <char, int> dictionary = new Dictionary <char, int>();
foreach(var c in str.ToLower())
    if (!dictionary.ContainsKey(c))
        dictionary.Add(c, 1);
    else
        dictionary[c]++;
foreach(var kvp in dictionary)
    Console.WriteLine(kvp.Key + "-" + kvp.Value);

或林克;

string str = "ssmmmjjkkkkrrr";
Dictionary<char, int> dictionary = str
    .ToLower()
    .GroupBy(c => c)
    .ToDictionary(c => c.Key, c => c.Count());
foreach (var kvp in dictionary)
    Console.WriteLine(kvp.Key + "-" + kvp.Value);