1. 程式人生 > >用c#實現文件的讀取和系列操作

用c#實現文件的讀取和系列操作

static filename ros ima git int lin {0} ase

Gitee代碼鏈接:https://gitee.com/hyr5201314/workcount

1.解題思路

首先要先讀取文件,然後調用函數實現返回文件的字符數,行數,單詞總數。用的是c#來做。

主要實現的功能:

wc.exe -c Mrhu.txt //返回文件 Mrhu.txt 的字符數

wc.exe -w Mrhu.txt //返回文件 Mrhu.txt 的單詞總數

wc.exe -l Mrhu.txt //返回文件 Mrhu.txt 的總行數

2,主要代碼說明

讀取文件

static void Main(string[] args)
{
string message = "";
while (message != "exit")
{
Console.Write("wc.exe ");
message = Console.ReadLine();
string[] arrMessSplit = message.Split(‘ ‘);
int Length = arrMessSplit.Length;
string[] sParameter = new string[Length - 1];
for (int i = 0; i < Length - 1; i++)
{
sParameter[i] = arrMessSplit[i];
}
// 獲取文件名
string sFilename = arrMessSplit[Length - 1];
WC wc = new WC();
wc.Operator(sParameter, sFilename);
wc.BaseCount(sFilename);
wc.Display();
wc.SaveResult();

}

統計行數,字符數,單詞數

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

}

輸出

public void SaveResult()
{
StreamWriter f = new StreamWriter(@"result.txt", false);
foreach (string a in sParameter)
{
if (a == "-c")
f.WriteLine("{0}字符數:{1}", sFilename, iCharcount);
if (a == "-w")
f.WriteLine("{0}單詞數:{1}", sFilename, iWordcount);
if (a == "-l")
f.WriteLine("{0}行數:{1}", sFilename, iLinecount);
}
f.Close();
Console.ReadKey();
}
public 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();

}

3.測試

技術分享圖片

5.參考文獻

https://social.msdn.microsoft.com/Forums/en-US/8a720549-0791-45ba-ab78-ca211ac959f5/streamreaderread?forum=visualcshartzhchs

用c#實現文件的讀取和系列操作