集合的三個練習
using System; using System.Collections; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace 練習 { class Program { static void Main(string[] args) { //將一個數組中的奇數放到一個集合中,再將偶數放到另外一個集合中 //最終將兩個集合合并為一個集合,并且奇數顯示在左邊 偶數顯示在右邊 int[] num = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 }; List<int> list1 = new List<int>(); List<int> list2 = new List<int>(); List <int> list3 = new List<int> (); for (int i = 0; i < num.Length; i++) { if (num[i] % 2 == 0) { list1.Add(num[i]); } else { list2.Add(num[i]); } } list3.AddRange(list2); list3.AddRange(list1); //for (int i = 0; i < list1.Count; i++) //{ // Console.WriteLine(list1[i]); //} //for (int i = 0; i < list2.Count; i++) //{ // Console.WriteLine(list2[i]); //} foreach (int item in list3) { Console.Write(item+" "); } Console.ReadKey(); } } }

using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace 練習2 { class Program { static void Main(string[] args) { //提示用戶輸入字符串,通過foreach循環將用過戶輸入的字符串賦值給一個字符數組 List<string> str = new List<string>(); for (int i = 0; i < 10; i++) { Console.WriteLine("請輸入字符串"); str.Add(Console.ReadLine()); } foreach (var item in str) { string[] s = new string[] {item}; for (int i = 0; i < s.Length ; i++) { Console.WriteLine(s[i]); } } Console.ReadKey(); }//sorry,寫錯了,題目寫錯了、、。、 } }

using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace 練習3 { class Program { static void Main(string[] args) { //統計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; } //如果dic已經包含了當前循環到的這個鍵,那么這個鍵的值就加一 if (dic.ContainsKey(str[i])) { dic[str[i]]++; } else//如果是第一次出現,那么這個字母的出現次數就是1,值就是1 { dic[str[i]] = 1; } } foreach (KeyValuePair<char, int> kv in dic) { Console.WriteLine("{0} {1}", kv.Key, kv.Value); } Console.ReadKey(); } } }


浙公網安備 33010602011771號