Files
CMLeonOS/shell/Commands/FileSystem/WordCountCommand.cs

51 lines
1.7 KiB
C#
Raw Permalink Normal View History

2026-02-04 20:13:21 +08:00
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}");
}
}
}
}