C#字符计数器

时间:2019-05-11 17:34:53

标签: c#

它一直显示“发生了异常!索引超出了 数组。”请帮忙。我添加了2个文本文件,其中一个放置了几个段落,另一个文本文件用于计算字符数。我不知道我在做什么错

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

 namespace ASCII
 {
      class CharacterFrequency
      {
          private char ch;
          private int frequency;

          public char Ch
          {
              get { return ch; }
              set { ch = value; }
          }
          public int Frequency
          {
              get { return frequency; }
              set { frequency = value; }
          }
     }
 }

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

 namespace ASCII
 {
     class Program
     {
          public string InputFileName = "";
          public string OutputFileName = "Count.txt";
          public string FilePath = "";

          public static SortedDictionary<char, ulong> Count(string stringToCount)
          {
              SortedDictionary<char, ulong> characterCount = new SortedDictionary<char, ulong>();

              foreach (var character in stringToCount)
              {
                  if (!characterCount.ContainsKey(character))
                  {
                      characterCount.Add(character, 1);
                  }
                  else
                  {
                      characterCount[character]++;
                  }
              }
              return characterCount;
          }

          static void Main(string[] args)
          {
              Program p = new Program();
              CharacterFrequency obj = new CharacterFrequency();
              StreamWriter streamWriter = new StreamWriter(p.OutputFileName);

              try
              {
                  p.InputFileName = args[0];
                  p.OutputFileName = args[1];
                  p.FilePath = Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location) + "\\" + p.InputFileName;
                  if (File.Exists(p.FilePath))
                  {
                      string data = File.ReadAllText(p.FilePath);
                      var count = Program.Count(data);
                      foreach (var character in count)
                      {
                          streamWriter.WriteLine(character.Key + "(" +  (int)character.Key + ")" + "\t" + character.Value);
                      }
                      streamWriter.Close();
                      Console.ReadLine();

                  }
                  else
                  {
                      Console.WriteLine("Please provide input File");
                  }
              }
              catch (Exception ex)
              {
                  Console.WriteLine("Exception occured! " + ex.Message.ToString());
                  Console.ReadLine();
              }
         }
    }
}

我需要它来计算字符。

0 个答案:

没有答案