如何计算字符串中出现的字符?
例如,假设我有以下输入字符串:
test text
输出应该是:
t 4
e 2
s 1
x 1
如果不编译和测试它,下面的 linq 应该可以解决问题:
from c in str
group by c into g
select new { letter= g.Key, count= g.Count()}
var str = "abc cccdd";
var group = from c in str
group c by c into g
select g;
foreach(var g in group)
{
Console.WriteLine(string.Format("{0}\t{1}", g.Key, g.Count()));
}
执行此操作的另一种方法,与 Luke McGregor 的回答相同,只是不同的语法
string mystring = "test text";
var result = mystring.GroupBy(ch => ch).Select(a => new {chr = a.Key, count = a.Count()});
递归解决方案
请注意,这也将计算空白。您之前可以删除空格。
public static void GroupString(string str)
{
if (str.Length == 1)
Console.WriteLine(str[0] + " 1");
else
{
Console.WriteLine(str[0] + " "+ str.Count(c => c == str[0]));
GroupString(str.Replace(str[0].ToString(),""));
}
}