题目一:编写C#程序,统计硬盘某个目录下的abc.txt文件中单词的个数。提示:要用到字符串类中的分割字符串等函数
源程序:
using System;
using System.IO;
using System.Linq;
using System.Text.RegularExpressions;
using System.Windows.Forms;
namespace 上机六
{
public partial class 统计单词数 : Form
{
public 统计单词数()
{
InitializeComponent();
StartPosition = FormStartPosition.CenterScreen;
}
private void button1_Click(object sender, EventArgs e)
{
string file = textBox1.Text;
if (!File.Exists(@file))
MessageBox.Show("文件" + @file + "不存在");
else
{
int a;
FileStream fs = new FileStream(@file, FileMode.Open, FileAccess.Read);
richTextBox1.Clear();
a = fs.ReadByte();
while (a != -1) //是否读到文件末尾
{
richTextBox1.Text += ((char)a).ToString();
a = fs.ReadByte();
}
fs.Close();
}
}
/*
* 正则表达式中“d”表示[0-9]的数字,“d+”表示由[0-9]的数字组成的数字,“w”表示[A-Z0-9],
* “w+”表示由数字、26 个英文字母或者下划线组成的字符串,“d+.+d+”表示小数
*/
private void button2_Click(object sender, EventArgs e)
{
Regex reg = new Regex("\S+\w+");
string InputStr = richTextBox1.Text;
int Count = reg.Split(InputStr).Count() - 1;
richTextBox2.Text = "单词个数:" + Count.ToString();
}
}
}
运行结果:
题目二:编写一个重复文件的检测程序:程序可以实现重复文件检测(即将硬盘某个盘符下的重复文件以ListBox控件列表的形式显示出来,例如:有1.doc、2.doc、3.doc完全一样,则这三个应该放在同一个ListBox1控件中;而a.exe、b.exe完全一样,则放在另一个ListBox2控件中)(可由设计者自行设计分组)。
源程序:
using System;
using System.Collections.Generic;
using System.IO;
using System.Windows.Forms;
namespace 上机六
{
public partial class 重复文件检测 : Form
{
public 重复文件检测()
{
InitializeComponent();
StartPosition = FormStartPosition.CenterScreen;
}
string path = @"D:demo";
string checktxt = "";
private void button1_Click(object sender, EventArgs e)
{
List<string> files = new List<string>();
ForeachFile(path, ref files);
foreach (var f in files)
{
try
{
string txt = "";
using (StreamReader sr = new StreamReader(f.ToString()))
{
string line;
while ((line = sr.ReadLine()) != null)