[英]Find no. of occurrence of each character in a string
给定一个字符串,我需要计算每个字符的实例数。 我的代码如下。 我希望很容易理解我的逻辑。
protected void btnSave_Click(object sender, EventArgs e)
{
var Firstname = txtFname.Text;
var lastName = txtLastName.Text;
var FullName = Firstname + "" + lastName;
char[] charArray = FullName.ToLower().ToCharArray();
Dictionary<char, int> counter = new Dictionary<char, int>();
int tempVar = 0;
foreach (var item in charArray)
{
if (counter.TryGetValue(item, out tempVar))
{
counter[item] += 1;
}
else
{
counter.Add(item, 1);
}
}
//var numberofchars = "";
foreach (KeyValuePair<char, int> item in counter)
{
if (counter.Count > 0)
{
//Label1.Text=split(item.
}
Response.Write(item.Value + " " + item.Key + "<br />");
}
}
这可能对你有用
string FullName = Firstname + "" + lastName;
var result = FullName.GroupBy(c => c)
.Where(c => c.Count() > 1)
.Select(c => new
{
charName = c.Key,
charCount = c.Count()
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.