C#7_31练习_计算字符串中每种字母出现的次数。

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Collections;


namespace ConsoleApplication27
{
    class Program
    {

//1、将int数组中的奇数放到一个新的int数组中返回
        static void Main(string[] args)
        {
            Console.WriteLine("将int数组中的奇数放到一个新的int数组中返回");
           
            ArrayList arr1 = new ArrayList(new int[] { 1, 2, 3, 4, 5, 6 });
            ArrayList arr2 = new ArrayList();
            for (int i = 0; i < arr1.Count; i++)
            {
                if (i % 2 != 0)
                {
                    arr2.Add(i);
                }
            }
            for (int j = 0; j < arr2.Count; j++)
            {
                Console.Write(arr2[j] + " ");
            }
            Console.WriteLine("\n"+"从一个整数的List<int> 中取出最大数,别用max 方法");
            //int temp = 0;
            //2、从一个整数的List<int> 中取出最大数,别用max 方法。
            List<int> arr = new List<int>();
            int[] a = { 1, 2,7,8, 3, 4 };//定义一个数组a
            arr.AddRange( a);//把数组添加到LIst<int> 的对象arr中
            arr.Sort();//从小到大排列arr的值
            arr.Reverse();//对arr进行一个逆向排序
            Console.WriteLine(arr[0]);//输出最大的值


            //3、计算字符串中每种字母出现的次数。
            Console.WriteLine("3、计算字符串中每种字母出现的次数。");
            string str = "wgfqhvdhjRLDMGKLE";//定义一串字符
            str = str.ToLower();//把字母都变成小写,不然一会计数的时候会重复计算同一个字母
            char[] ch = str.ToCharArray();//把str变成一个char类型的数组。
            Dictionary <char,int> dic= new  Dictionary<char, int>();//定义一个泛型版本的集合
            for(int i = 0; i < ch.Length; i++)
            {
                if (char.IsLetter(ch[i])) //判断字符是否为字母类型
                {
                    if (!dic.ContainsKey(ch[i]))//如果是字母类型,则判断dic的键是否包含该字符
                    {
                        dic.Add(ch[i], 1);//如果不是dic的键,就把他变为dic的键,值为1
                    }
                    else//如果dic的键包含该字符,对应的值加1
                    {
                        dic[ch[i]] = dic[ch[i]] + 1;
                    }                         
                }
            }
            foreach(KeyValuePair<char,int> dic1 in dic)//遍历输出
            {
                Console.WriteLine("字母{0}出现的次数是:{1}",dic1.Key,dic1.Value);
            }
            Console.ReadLine();
           }
        
    }
}
 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章