Gitee代码地址:https://gitee.com/wyygysj/codes/8usmktry64ix0n3po1aeq21

此项目我只实现了基本功能,即字符、行数、单词数的计算以及将结果输出到文件中。

该项目用C#语言进行实现。

解题思路:

    根据题目要求所知,需要读取一个文件中的内容,然后再计算文件内容的字符数,单词数,行数等,再将结果输出到另一个即result文件中。

所以要考虑文件的读取和输出,对单词数,字符数,行数如何计算,还有命令的输入和读取。

WordCount需求说明

WordCount的需求可以概括为:对程序设计语言源文件统计字符数、单词数、行数,统计结果以指定格式输出到默认文件中,以及其他扩展功能,并能够快速地处理多个文件。

可执行程序命名为:wc.exe,该程序处理用户需求的模式为:

wc.exe [parameter] [input_file_name]

存储统计结果的文件默认为result.txt,放在与wc.exe相同的目录下。

代码实现

字符数计算:

 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;
        }

测试结果:

 

 

  这是在室友的帮助下完成的。