我想用c#.net计算字符串中每个唯一的字母

时间:2011-01-12 13:46:53

标签: c#

我想写一个问题,从命令行读取文本文件,并输出每个唯一字母的计数,按字母顺序排序。在C#中对此程序的任何建议 示例:

堆栈溢出

输出:

1 c 1 k 1 t 1 s 2

4 个答案:

答案 0 :(得分:5)

正如其他人所说,这听起来像是家庭作业。我会给你一些提示:

  • 拆分任务。 “处理”代码不需要依赖于来自文件的输入或输出到屏幕的输入。
  • 如果您被允许,请查看LINQ,它以非常易于使用的方式提供排序,分组和计数功能。
  • 对于奖励积分,实施处理部分的单元测试......

答案 1 :(得分:1)

使用LINQ,获取唯一字符的一种方法是:

string s = "Stack Overflows";

var x = from c in s.ToLower()
        group c by c into a
        select new { a.Key, Count = a.Count() };

答案 2 :(得分:0)

        string s = "stack overflows";
        Dictionary<char, int> dic = new Dictionary<char, int>();

        foreach (char x in s)
        {

            if (dic.ContainsKey(x) == true) 
            {

                dic[x] += 1;
            }
            else
            {
                dic.Add(x, 1);

            }

        }
        foreach (KeyValuePair<char, int> x in dic)
        {

            Console.WriteLine(x.Key + " " + x.Value);

        }

答案 3 :(得分:0)

班级考试     {

    static void Main(string[] args)
    {
        string inputstring = "stackOverflows";
        charcount(inputstring, inputstring.ToCharArray()[0]);
    }

    public static void charcount(string recstring ,char c )
    {
        if (recstring.Length != 0)
        {
            int count = 0;
            foreach (char c1 in recstring)
            { if (c1==c)
            {

                count++;
            }

            }
            Console.WriteLine(c+"  "+count);
            string tempstring = recstring.Replace(char.ToString(c), "");
            if (tempstring.Length != 0)
            {
                charcount(tempstring, tempstring.ToCharArray()[0]);
            }
        }

    }
相关问题