集合中的3个经典练习题

            //将一个数组中的奇数放到一个集合中,再将数组的偶数放到另一个集合中。
            //最终将两个集合合并为一个集合,并且奇数显示在左边,偶数显示在右边。
            int[] nums = { 1, 2, 3, 4, 5, 6, 7, 8, 9 };
            ArrayList list1 = new ArrayList();
            ArrayList list2 = new ArrayList();
            for (int i = 0; i < nums.Length; i++)
            {
                if (nums[i] % 2 == 0)
                {
                    list1.Add(nums[i]);
                }
                else
                {
                    list2.Add(nums[i]);
                }
            }
            list2.AddRange(list1);
            foreach (var item in list2)
            {
                Console.Write(item + " ");
            }
            Console.ReadLine();
            //提示用户输入一个字符串,通过foreach循环将用户输入的字符串
            ////赋值给另一个字符数组
            Console.WriteLine("请输入一个字符串");
            string input = Console.ReadLine();
            char[] chs = new char[input.Length];
            int i = 0;
            foreach (var item in input)
            {
                chs[i] = item;
                i++;
            }
            foreach (var item in chs)
            {
                Console.Write(item + " ");
            }
            Console.ReadLine();
            //统计 welcome to china中每个字符出现的次数,不考虑大小写。
            string str = "Welcome to China";
            //思路:字符------>出现次数
            //键-------->值
            Dictionary<char, int> dic = new Dictionary<char, int>();
            for (int i = 0; i < str.Length; i++)
            {
                if (str[i] ==' ')
                {
                    continue;
                }
                if (dic.ContainsKey(str[i]))  //如果dic已经包含了当前循环到的这个键
                {
                    //其键对应的值的数量+1
                    dic[str[i]]++;
                }
                else//表示这个字符在集合当中是第一次出现
                {
                    dic[str[i]] = 1;
                }
            }
            foreach (KeyValuePair<char,int> kv in dic)
            {
                Console.WriteLine("字母{0}出现了{1}次",kv.Key,kv.Value);
            }
            Console.ReadLine();
原文地址:https://www.cnblogs.com/kangshuai/p/4698884.html