计算字符串C#中所有字符的出现次数 [英] Count All Character Occurrences in a String C#

查看:313
本文介绍了计算字符串C#中所有字符的出现次数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

动态计数C#中每个字符出现的最佳方法是什么?

What is the best way to dynamically count each character occurrence in C#?

给定

string sample = "Foe Doe";

它应该输出类似

f = 1
o = 2
e = 2
d = 1

对单个字符计数很容易,但是在我的考试中这有点棘手,我只能想象得到所有唯一字符的解决方案->然后将其存储在一个集合中(最好是一个数组),然后

counting a single character would be easy but in my exam this was a bit tricky, I could only imagine a solution to get all unique characters -> then store it in a collection(preferably an array) then a nested for loop for the array and the string.

有没有比这更好的解决方案了?

Is there a better solution than this?

推荐答案

使用LINQ

sample.GroupBy(c => c).Select(c => new { Char = c.Key, Count = c.Count()});

这篇关于计算字符串C#中所有字符的出现次数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆