星期一, 6月 12, 2017

[C#] 計算檔案內每個英文出現的次數

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

namespace ConsoleCalEng
{
    class Program
    {
        static void Main(string[] args)
        {
            string input ;
            string fileName;
            char cha;
            int k;
            FileInfo f;
            StreamReader sr;
            Console.WriteLine("Please inpt the File path:");
            input = Console.ReadLine();
            f = new FileInfo(input);
            try
            {
                sr = f.OpenText();
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);

                return;
            }
            int[] letter = new int[26];

            while (sr.Peek() >= 0)
            {
                cha = (char)sr.Read();
                if (cha >= 'A' && cha <= 'Z')
                {
                    k = (int) cha - 65;
                    letter[k]++;
                }
                 if (cha >= 'a' && cha <= 'z'){
                         k = (int) cha - 97;
                         letter[k]++;
                 }
            }
                 Console.WriteLine("該檔案各英文出現的次數:");
                 for (int i = 0; i < 26; i++)
                 {
                     Console.WriteLine("{0},{1} 出現的次數:{2}",(char)(65+i),(char)(97+i),letter[i]);
                 }
     
            sr.Close();
            Console.Read();
        }
    }
}

沒有留言: