我有一个字符串如下:
string str = "ssmmmjjkkkkrrr"
使用C#,我需要显示每个字符的计数,如下所示:
s = 2
m = 3
j = 2
k = 4
r = 3
提前致谢。
答案 0 :(得分:17)
最简单的方法是使用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());
}
答案 1 :(得分:5)
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);
}
答案 2 :(得分:4)
由于每个人都提供了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]);
答案 3 :(得分:1)
mystring.GroupBy(ch => ch)
.Select(a => new { ch = a.Key, count = a.Count() })
.ToList()
.ForEach(x => Console.WriteLine("{0} = {1}", x.ch, x.count));