编写一个接受字符数组作为输入的函数,计算数组中每个字符的出现次数,并以格式输出结果(例如{' c',' e&# 39;,' e','' a',' q'}
a - *
c - *
e - ***
q - *
我再次尝试使用字典但是如何获得星号
class Program
{
public static void Main()
{
char[] characters = { 'c', 'e', 'e', 'e', 'a', 'q' };
charFuction(characters);
}
static Dictionary<char, int> occurrences = new Dictionary<char, int>();
static void charFuction(char[] characters)
{
foreach(char c in characters)
{
if (occurrences.ContainsKey(c))
{
occurrences[c]++;
}
else
{
occurrences.Add(c, 1);
}
}
foreach(char k in occurrences.Keys)
{
Console.WriteLine(k + " - " + occurrences[k]);
}
}
答案 0 :(得分:1)
使用LINQ:
public static IEnumerable<string> GetCharCountPlaceholders(IEnumerable<char> chars, char placeholder = '*', string charCountDelimiter = " - ")
{
return chars
.GroupBy(c => c)
.OrderBy(g => g.Key)
.Select(g => String.Format("{0}{1}{2}"
, g.Key
, charCountDelimiter
, new String(placeholder, g.Count())));
}
您可以通过这种方式调用它:
char[] chars = { 'c', 'e', 'e', 'e', 'a', 'q' };
string result = String.Join(Environment.NewLine, GetCharCountPlaceholders(chars));
a - *
c - *
e - ***
q - *