使用数组列表的字符计数器

时间:2018-11-21 01:18:55

标签: c# arrays arraylist

我需要设计一个程序,该程序读取ASCII文本文件并创建一个输出文件,其中包含每个唯一的ASCII字符及其在文件中出现的次数。文件中的每个唯一字符都必须由一个字符频率类实例表示。字符频率对象必须存储在数组列表中。我的代码如下:

using System.IO;
using System;
using System.Collections;

namespace ASCII
{
    class CharacterFrequency
    {
        char ch;
        int frequency;
        public char getCharacter()
        {
            return ch;
        }
        public void setCharacter(char ch)
        {
            this.ch = ch;
        }
        public int getfrequency()
        {
            return frequency;
        }
        public void setfrequency(int frequency)
        {
            this.frequency = frequency;
        }


        static void Main()
        {
            string OutputFileName;
            string InputFileName;
            Console.WriteLine("Enter the file path");
            InputFileName = Console.ReadLine();

            Console.WriteLine("Enter the outputfile name");
            OutputFileName = Console.ReadLine();
            StreamWriter streamWriter = new StreamWriter(OutputFileName);

            string data = File.ReadAllText(InputFileName);


            ArrayList al = new ArrayList();

            //create two for loops to traverse through the arraylist and compare

            for (int i = 0; i < data.Length; i++)
            {
                int k = 0;
                int f = 0;
                for (int j = 0; j < data.Length; j++)
                {
                    if (data[i].Equals(data[j]))
                    {
                        f++;                        
                        if (i > j) { k++; }
                    }
                }


                al.Add(data[i] + "(" + (int)data[i] + ")" + f + " ");

                foreach (var item in al)
                {
                    streamWriter.WriteLine(item);
                }


            }


            streamWriter.Close();

        }
    }
} 

当我运行该程序时,该程序不会停止运行,并且输出文件会不断变大,直到最终耗尽内存为止,并且出现错误指出。我看不到错误在哪里或为什么循环不会终止。它应该只计算字符,但似乎不断循环并重复计算字符。有帮助吗?

1 个答案:

答案 0 :(得分:0)

尝试这种方法:

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

namespace yourNamespace
{
    class Char_frrequency
    {
    Dictionary<Char, int> countMap = new Dictionary<char, int>();

    public String getStringWithUniqueCharacters(String input)
    {

        List<Char> uniqueList = new List<Char>();


        foreach (Char x in input)
        {
            if (countMap.ContainsKey(x))
            {
                countMap[x]++;
            }
            else
            {
                countMap.Add(x, 1);
            }


            if (!uniqueList.Contains(x))
            {
                uniqueList.Add(x);
            }
        }
        Char[] uniqueArray = uniqueList.ToArray();
        return new String(uniqueArray);
    }

    public int getFrequency(Char x)
    {
        return countMap[x];
    }
}
}

这可能不是理想的解决方案。但是您可以使用这些方法