找不到。字符串中每个字符的出现次数

时间:2017-01-25 04:26:12

标签: c#

给定一个字符串,我需要计算每个字符的实例数。我的代码如下。我希望很容易理解我的逻辑。

    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 />");  
        }
    }

1 个答案:

答案 0 :(得分:0)

这可能会为你做到这一点

string FullName = Firstname + "" + lastName;
var result = FullName.GroupBy(c => c)
                     .Where(c => c.Count() > 1)
                     .Select(c => new 
                                    { 
                                        charName = c.Key, 
                                        charCount = c.Count()
                                    });