我正在尝试创建一个程序,该程序对文件中的ASCII字符进行计数,并跟踪每个字符在文件中出现的次数。然后,应将输出写入文件。如果文件仅显示为“ Hello”,则输出文件的格式应显示为:
H(72)1 e(101)1 l(108)2 o(111)1 (46)1
我到目前为止编写的代码如下:
using System.IO;
using System;
using System.Collections;
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();
al.Add(data);
//create two for loops to traverse through the arraylist and compare
for (int i = 0; i < al.Count; i++)
{
//create variable k to count the repeated element
//(if k>0 it means that the particular element is not the first instance)
int k = 0;
//count frequency variable
int f = 0;
for (int j = 0; j < al.Count; j++)
{
//compare the characters
if (al[i].Equals(al[j]))
{
f++;
if (i > j) { k++; }
}
}
if (k == 0)
{
//Display in the correct format
Console.Write(al[i] + "(" + (int)al[i] + ")" + f + " ");
}
}
}
}
在代码的最后一行(Console.Write)上出现错误,指出:“指定的强制转换无效。”我知道该程序可能无法正确编写,但是我很难使用数组列表来完成此任务。我已经在以前的程序中使用排序字典完成了此任务,但是现在我必须使用数组列表。非常感谢您提供有关如何纠正错误以及程序外观的任何建议。
答案 0 :(得分:0)
保持类似的效果,我可以运行它。如果将其保留为字符串并将其视为char数组,则效果很好。
string data = "Hello";
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++; }
}
}
//Display in the correct format
Console.Write(data[i] + "(" + (int)data[i] + ")" + f + " ");
}