05.泛型集合的练习

练习1:将一个数组中的奇数放到一个集合中,再将偶数放到另一个集合中.最终将两个集合合并为一个集合,并且奇数显示在左边,偶数显示在右边.
 
   
  1. namespace _12.集合的练习01
  2. {
  3. class Program
  4. {
  5. static void Main(string[] args)
  6. {
  7. /*
  8. 将一个数组中的奇数放到一个集合中,再将偶数放到另一个集合中.
  9. 最终将两个集合合并为一个集合,并且奇数显示在左边,偶数显示在右边.
  10. */
  11. int[] iArray = {1,2,3,4,5,6,7,8,9,10};
  12. List<int> a = new List<int>(); //用来保存偶数
  13. List<int> b = new List<int>(); //用来保存奇数
  14. List<int> ab = new List<int>(); //用来保存a+b集合的
  15. for (int i = 0; i < iArray.Length; i++)
  16. {
  17. if (iArray[i] % 2 == 0)
  18. {
  19. a.Add(iArray[i]);
  20. }
  21. else
  22. {
  23. b.Add(iArray[i]);
  24. }
  25. }
  26. b.AddRange(a);
  27. foreach (var item in b)
  28. {
  29. Console.Write(item);
  30. }
  31. Console.ReadKey();
  32. }
  33. }
  34. }


练习2:提示用户输入一个字符串,通过foreach循环将用户输入的字符串赋值给一个字符数组.  
 
   
  1. namespace _13.集合的练习02
  2. {
  3. class Program
  4. {
  5. static void Main(string[] args)
  6. {
  7. /*
  8. 提示用户输入一个字符串,
  9. 通过foreach循环将用户输入的字符串赋值给一个字符数组.
  10. */
  11. Console.WriteLine("请输入一个字符串:");
  12. string str = Console.ReadLine();
  13. char[] c1 = new char[str.Length];
  14. int i = 0;
  15. foreach (var item in str) //我们可以将str看成是一个只读的字符数组,所以item中装的是字符
  16. {
  17. c1[i] = item;
  18. i++;
  19. }
  20. for (int j = 0; j < c1.Length; j++)
  21. {
  22. Console.Write(c1[j]);
  23. }
  24. Console.ReadKey();
  25. }
  26. }
  27. }


练习3: 统计welcome to china中每一个字符出现的次数,不考虑大小写.(面试题)
 
   
  1. namespace _14.集合的练习03
  2. {
  3. class Program
  4. {
  5. static void Main(string[] args)
  6. {
  7. /*
  8. 统计welcome to china中每一个字符出现的次数,不考虑大小写.(面试题)
  9. */
  10. string str = "Welcome to China";
  11. //字符---->出现的次数
  12. //键----->值
  13. Dictionary<char,int> dic= new Dictionary<char, int>();
  14. for (int i = 0; i < str.Length; i++)
  15. {
  16. if (str[i] == ' ')
  17. {
  18. continue;
  19. }
  20. //如果dic这个键值对集合中已经包含了当前循环的键,
  21. if (dic.ContainsKey(str[i]))
  22. {
  23. dic[str[i]]++;
  24. }
  25. else //这个字符在集合中是调用此出现
  26. {
  27. dic[str[i]] = 1;
  28. }
  29. }
  30. foreach (KeyValuePair<char,int> item in dic)
  31. {
  32. Console.WriteLine("字母:{0}出现了{1}次.",item.Key,item.Value);
  33. }
  34. Console.ReadKey();
  35. }
  36. }
  37. }






转载于:https://www.cnblogs.com/HelloZyjS/p/6038281.html

  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值