一.Gitee代码链接:https://gitee.com/c0514/codes/new
二.解题思路:
1)首先考虑如何统计文件单词数,可以将一个非分隔符(如‘,’,‘ ’)作为一个新单词计数的开始,分隔符作为该单词的结束,行数的统计可以根据‘\n‘的数量来统计。
3)考虑如何利用C#相关函数读取文件内容,以及如何写入文件内容。
3.代码片段:
分离命令参数和文件名:
string[] strs = { "one", "two", "three" }; string s = ""; for (int i = 0; i < strs.Length - 1; i++) { s = s + strs[i] + "|"; s = s + strs[strs.Length - 1]; Console.WriteLine(s); Console.ReadKey(); } string message = ""; // 存储用户命令 while (message != "exit") { Console.Write("wc.exe "); message = Console.ReadLine(); // 得到输入命令 string[] arrMessSplit = message.Split(‘ ‘); // 分割命令 int iMessLength = arrMessSplit.Length; string[] sParameter = new string[iMessLength - 1]; // 获取命令参数数组 for (int i = 0; i < iMessLength - 1; i++) { sParameter[i] = arrMessSplit[i]; } // 获取文件名 string sFilename = arrMessSplit[iMessLength - 1]; }
在Operator()方法中,捕捉 "-c"、"-w"、"-l" 命令,通过参数素组的设置调用不同的类方法进行处理;Display()方法用来打印输出信息; BaseCount() 方法用以统计指定文件的字符数、单词数以及总行数。
我们首先填充 Operator() 方法,此方法在参数数组中包含 "-c" 或 "-w" 或 "-l" 时调用 BaseCount() 方法实现文件基本信息的统计,调用 Display() 方法打印结果。代码如下:
public void Operator(string[] sParameter, string sFilename) { this.sParameter = sParameter; this.sFilename = sFilename; foreach (string s in sParameter) { // 基本功能 else if (s == "-c" || s == "-w" || s == "-l") { break; } else { Console.WriteLine("参数 {0} 不存在", s); break; } } }
在 BaseCount() 中,通过传入的文件名对文件进行读取。并进行字符数、单词数、总行数的判断。判断规则如下
private void BaseCount(string filename) { try { // 打开文件 FileStream file = new FileStream(filename, FileMode.Open, FileAccess.Read, FileShare.Read); StreamReader sr = new StreamReader(file); int nChar; int charcount = 0; int wordcount = 0; int linecount = 0; //定义一个字符数组 char[] symbol = { ‘ ‘, ‘\t‘, ‘,‘, ‘.‘, ‘?‘, ‘!‘, ‘:‘, ‘;‘, ‘\‘‘, ‘\"‘, ‘\n‘, ‘{‘, ‘}‘, ‘(‘, ‘)‘, ‘+‘ ,‘-‘, ‘*‘, ‘=‘}; while ((nChar = sr.Read()) != -1) { charcount++; // 统计字符数 foreach (char c in symbol) { if (nChar == (int)c) { wordcount++; // 统计单词数 } } if (nChar == ‘\n‘) { linecount++; // 统计行数 } } iCharcount = charcount; iWordcount = wordcount + 1; iLinecount = linecount + 1; sr.Close(); } catch (IOException ex) { Console.WriteLine(ex.Message); return; } }
接下来,我们只需要将统计信息打印出来,就完成了基本功能的实现。
private void Display() { foreach (string s in sParameter) { if (s == "-c") { Console.WriteLine("字 符 数:{0}", iCharcount); } else if (s == "-w") { Console.WriteLine("单 词 数:{0}", iWordcount); } else if (s == "-l") { Console.WriteLine("总 行 数:{0}", iLinecount); } } Console.WriteLine(); }
至此,我们基本实现了 Test.exe 的基本功能。
原文:https://www.cnblogs.com/c0514/p/9732492.html