Gitee代码地址:https://gitee.com/FreedomWar/codes/q32yd7g4respuf9ljh0oc40
此项目我只实现了基本功能,即字符、行数、单词数的计算以及将结果输出到文件中。
该项目用C#语言进行实现。
解题思路:
根据题目要求所知,需要读取一个文件中的内容,然后再计算文件内容的字符数,单词数,行数等,再将结果输出到另一个即result文件中。
所以要考虑文件的读取和输出,对单词数,字符数,行数如何计算,还有命令的输入和读取。
WordCount需求说明
WordCount的需求可以概括为:对程序设计语言源文件统计字符数、单词数、行数,统计结果以指定格式输出到默认文件中,以及其他扩展功能,并能够快速地处理多个文件。
可执行程序命名为:wc.exe,该程序处理用户需求的模式为:
wc.exe [parameter] [input_file_name]
存储统计结果的文件默认为result.txt,放在与wc.exe相同的目录下。
部分代码实现:
主函数代码:
static
void
Main(
string
[] args)
{
string strcomm = Console.ReadLine();
ProcessingData wc = new ProcessingData();
string[] sArray = strcomm.Split(new char[2] { ‘ ‘, ‘-‘ }, StringSplitOptions.RemoveEmptyEntries);//去空格截取各个字符串信息
for (int i = 1; i < sArray.Length - 1; i++)
{
switch (sArray[i])
{
//Convert .ToInt32 (
case "c":
Console.WriteLine(sArray[sArray.Length - 1] + " 字符数:" + wc.cProsess(sArray[sArray.Length - 1]));
break;
case "w":
Console.WriteLine(sArray[sArray.Length - 1] + " 单词数:" + wc.wProsess(sArray[sArray.Length - 1]));
break;
case "l":
Console.WriteLine(sArray[sArray.Length - 1] + " 行数:" + wc.lProsess(sArray[sArray.Length - 1]));
break;
case "o":
Console.WriteLine(wc.oProcess(sArray[sArray.Length - 1]));
break;
default:
Console.WriteLine("输入的指令 -" + sArray[i] + " 有误!");
break;
}
}
Console.ReadKey();
}
字符数计算:
public int cProcess(string fstr)
{
string str = openFile(fstr);
int charCount = 0;//记录字符个数
foreach (char c in str)
{
if (c == ‘ ‘ || c == ‘\t‘ || c == ‘\n‘)
{
break;
}
else
{
charCount++;
}
}
StreamWriter sw = new StreamWriter("result.txt", true);
sw.WriteLine(fstr + " 字符数: " + Convert.ToString(charCount));
sw.Close();
return charCount;
}
单词数计算:
public int wProcess(string wstr)
{
string str = openFile(wstr);
int count = 0;//记录单词个数
bool flag = true;
foreach (char s in str)//遍历字符串,
{
if (s != ‘ ‘ && s != ‘\n‘ && flag == true)
{
count++;
flag = false;
}
else if ((s == ‘ ‘ || s == ‘\n‘) && flag == false)
{
flag = true;
}
}
StreamWriter sw = new StreamWriter("result.txt", true);
sw.WriteLine(wstr + " 单词数:" + Convert.ToString(count - 1));//
sw.Close();
return count ;
}
行数计算:
public int lProcess(string lstr)
{
string str = openFile(lstr);
int count = 0;//记录行数
foreach (char s in str)
{
if (s == ‘\n‘)
{
count++;
}
}
StreamWriter sw = new StreamWriter("result.txt", true);
sw.WriteLine(lstr + " 行数: " + Convert.ToString(count - 1));
sw.Close();
return count + 1;
}
测试结果:
参考文献:
关于写入文件的操作 http://www.cnblogs.com/duanjt/p/5265655.html
原文:https://www.cnblogs.com/a1289814983/p/9697348.html