mirror of
https://github.com/Leonmmcoset/CMLeonOS.git
synced 2026-03-03 15:30:27 +00:00
拆分代码4
This commit is contained in:
50
shell/Commands/FileSystem/WordCountCommand.cs
Normal file
50
shell/Commands/FileSystem/WordCountCommand.cs
Normal file
@@ -0,0 +1,50 @@
|
||||
using System;
|
||||
|
||||
namespace CMLeonOS.Commands.FileSystem
|
||||
{
|
||||
public static class WordCountCommand
|
||||
{
|
||||
public static void WordCount(CMLeonOS.FileSystem fileSystem, string args, Action<string> showError)
|
||||
{
|
||||
if (string.IsNullOrEmpty(args))
|
||||
{
|
||||
showError("Please specify a file name");
|
||||
return;
|
||||
}
|
||||
|
||||
try
|
||||
{
|
||||
string content = fileSystem.ReadFile(args);
|
||||
if (string.IsNullOrEmpty(content))
|
||||
{
|
||||
Console.WriteLine("File is empty");
|
||||
return;
|
||||
}
|
||||
|
||||
string[] lines = content.Split(new string[] { "\r\n", "\n" }, StringSplitOptions.None);
|
||||
int lineCount = lines.Length;
|
||||
int wordCount = 0;
|
||||
int charCount = content.Length;
|
||||
|
||||
foreach (string line in lines)
|
||||
{
|
||||
if (!string.IsNullOrWhiteSpace(line))
|
||||
{
|
||||
string[] words = line.Split(new char[] { ' ', '\t' }, StringSplitOptions.RemoveEmptyEntries);
|
||||
wordCount += words.Length;
|
||||
}
|
||||
}
|
||||
|
||||
Console.WriteLine($"Word count for {args}:");
|
||||
Console.WriteLine("--------------------------------");
|
||||
Console.WriteLine($"Lines: {lineCount}");
|
||||
Console.WriteLine($"Words: {wordCount}");
|
||||
Console.WriteLine($"Characters: {charCount}");
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
showError($"Error reading file: {ex.Message}");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user