已知一个字符串,如“djsdfkdkfdkfj”,求出字符串中有多少种字符,以及每种字符的个数。
用c#编写,用数组实现。希望大家各显神通,多写出几种算法来

解决方案 »

  1.   


                String str = "djsdfkdkfdkfj";            List<Char> listC = new List<Char>();
                List<Int32> listN = new List<Int32>();            for (Int32 i = 0; i < str.Length; i++)
                {
                    Char c = str[i];                if (listC.Contains(c))
                    {
                        Int32 index = listC.IndexOf(c);
                        listN[index] = listN[index] + 1;
                    }
                    else
                    {
                        listC.Add(c);
                        listN.Add(1);
                    }
                }            for (Int32 j = 0; j < listC.Count; j++)
                {
                    Console.WriteLine(listC[j] + " : " + listN[j]);
                }
      

  2.   

    string str="djsdfkdkfdkfj";
    while(str.length>0)
    {  
    string s=str.substring(1,1);
    console.Writtline("字符{0}有{1}个",s,str.length-str.replace(s,"").length);
    str=str.replace(s,"");
    }手写的
      

  3.   

    //经测试通过,但没用数组,用的是Dictionary
    string str = "djsdfkdkfdkfj";
    Dictionary<char, int> freq = new Dictionary<char, int>();
    while (str.Length > 0)
    {
    char ch = str[0];
    string s = str.Replace(ch.ToString(), string.Empty);
    freq.Add(ch, str.Length - s.Length);
    str = s;
    }
      

  4.   

    [code]
        [Test]
        public void Test1()
        {
          String str = "djsdfkdkfdkfj";
          var lu = (from c in str
                    select c).GroupBy(c => c);
          Console.WriteLine(lu.Count());
          foreach (var l in lu)
          {
            Console.WriteLine("{0} : {1}", l.Key, l.Count());
          }
        }
    [/code]
      

  5.   

        [Test]
        public void Test1()
        {
          String str = "djsdfkdkfdkfj";
          var lu = (from c in str
                    select c).GroupBy(c => c);
          Console.WriteLine(lu.Count());
          foreach (var l in lu)
          {
            Console.WriteLine("{0} : {1}", l.Key, l.Count());
          }
        }