计算一个字符在文本文件中出现的次数
本文关键字:文件 文本 字符 一个 计算 | 更新日期: 2023-09-27 18:27:34
我正在学习C#,我想计算一个字符在文本文件中出现的次数。用户输入文本文件的路径和要搜索的字符。程序当前找不到任何字符。我做错了什么?这是代码:
public static void Main(string[] args)
{
string fileName;
fileName = readInput("Please enter the path to the file: ");
StreamReader fromFile = new StreamReader(fileName);
string line;
while ((line = fromFile.ReadLine()) != null)
{
Console.WriteLine(line);
}
int count = 0;
char search;
search = readSearch("Please enter the character you want to search for: ");
while ((line = fromFile.ReadLine()) != null)
{
foreach (char letter in line)
{
if (search == letter)
{
count ++;
}
}
}
Console.WriteLine("{0} was found {1} time(s).", search, count);
Console.ReadLine();
fromFile.Close();
Console.ReadLine();
}
private static string readInput(string questionPath)
{
Console.Write(questionPath);
string input = Console.ReadLine();
return input;
}
private static char readSearch(string questionSearch)
{
Console.Write(questionSearch);
char input = Convert.ToChar(Console.Read());
return input;
}
}
看起来是在计算匹配的字符之前将文件写入屏幕。这样做时,您可以将StreamReader
移动到文件的末尾,而不重置它。每次重置读取器(并使用using
):
StreamReader fromFile;
using(fromFile = new StreamReader(fileName))
{
string line;
while ((line = fromFile.ReadLine()) != null)
{
Console.WriteLine(line);
}
}
int count = 0;
char search;
search = readSearch("Please enter the character you want to search for: ");
using(fromFile = new StreamReader(fileName))
{
while ((line = fromFile.ReadLine()) != null)
{
//....
}
}
或者您可以先将文件读入内存。
问题是您已经通读了整个流。一个简单的修复方法是从头开始重新启动读取。这可以通过在开始计数操作之前执行以下操作来完成:
fromFile.BaseStream.Seek(0, SeekOrigin.Begin);
作为附加信息,您可以将计数操作替换为LINQ语句。更换:
foreach (char letter in line)
{
if (search == letter)
{
count++;
}
}
带有:
count += line.Count(letter => search == letter);
此代码将打开一个文件,计算其中每个字符的数量,并将总数输出到另一个文件。
if (File.Exists(charCountFileName)) File.Delete(charCountFileName);
SortedDictionary<ushort, int> charsDict = new SortedDictionary<ushort, int>();
using (StreamReader r = new StreamReader(inputFileName))
{
char[] buffer = new char[1024];
int read;
while ((read = r.ReadBlock(buffer, 0, buffer.Length)) > 0)
{
for (int i = 0; i < read; i++)
{
if (!charsDict.ContainsKey((ushort)buffer[i]))
{
charsDict.Add((ushort)buffer[i], 1);
}
else
charsDict[(ushort)buffer[i]]++;
}
}
}
using (StreamWriter file = new StreamWriter(new FileStream(charCountFileName, FileMode.Create), Encoding.UTF8))
foreach (var entry in charsDict)
file.WriteLine("{0}'t{1}'t{2}", entry.Key, Convert.ToChar(entry.Key), entry.Value);