计算给定字符串中的所有字符 [英] count the all characters in a given string

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

问题描述

你好

给定一个字符串,例如"basheer",我怎么能给定字符串中所有给定的字符实例并将其输出?我要的样本是:

b = 1
a = 1
s = 1
h = 1
e = 2
r = 1

问候
Basheer

Hello

Given a string such as "basheer", how would I could all the given instances of the characters in the string and output it? The sample I''m after is:

b=1
a=1
s=1
h=1
e=2
r=1

Regards
Basheer

推荐答案

一种简单的方法是使用Dictionary<char, int>来表示字母和实例数.从左边的字符开始,然后朝着最后一个字符前进.对于每个字符,请检查其是否已在字典中.如果增加,则计数.如果不是,则在其中添加字符并将计数设置为1.

还有其他实现复杂程度不同的方法,但是请记住,将来您将必须支持此方法,这似乎是一项家庭作业问题,因此不必过分担心性能.作业的重要之处在于代码的清晰度,并表明您了解原理-这就是我刚刚告诉您所要应用的逻辑的全部原因,而实际上没有给您代码.可以用来证明您确实了解这些原理.
A simple way to achieve this would be to use a Dictionary<char, int> which represents the letter and the count of instances. Start at the left character and work your way towards the last character. With each character, check to see if it''s already in the dictionary. If it is increment the count. If it isn''t, add the character in and set the count to 1.

There are other ways to achieve this, of varying complexity, but remember that you are going to have to support this in the future, and this looks to be a homework question so don''t worry about the performance too much. The important thing with homework is clarity of code, and demonstrating that you understand the principals - this is the whole reason I''ve just told you what the logic is that you would apply, and haven''t actually given you the code; that is left to you to prove that you do understand the principals.


可以使用IEnumerable接口的GroupBy extension方法和Count extension方法,如下所示:

The GroupBy extension method and Count extension methods of IEnumerable interface can be used as shown below:

void Main()
{
	string str="basheer";
	List<string> charCounts = str.GroupBy (ch => ch).Select (
			item => item.Key + "=" + item.Count().ToString()).ToList();
	foreach (string  s in charCounts)
	{
		Console.WriteLine (s);		
	}
	
}
//Output
//b=1
//a=1
//s=1
//h=1
//e=2
//r=1


请参阅此链接:
http://forums.asp.net/post/2613305.aspx [
Refer to this link:
http://forums.asp.net/post/2613305.aspx[^]


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

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