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();
           }
        
    }
}
 

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