Skip to main content
 首页 » 编程设计

c#之IRC聊天命令解析

2024年02月13日12三少

固定 我将代码放在这里,供其他需要帮助解决自己问题的人使用(假设他们遇到了我遇到的问题。

FIXED CODE THAT WORKS 
 
    public static bool CommandExists(String value) 
    { 
        string[] commands = File.ReadAllText("commands.txt") 
                       .Split() 
                       .Where(x => x.StartsWith(value)) 
                       .Distinct() 
                       .ToArray(); 
        return commands.Contains(value); 
    } 
    public static string CommandParse(String value, string nick) 
    { 
        IEnumerable<string> lines; 
        lines = File.ReadLines("commands.txt"); 
        IEnumerable<string> command = lines 
            .Where(d => d.StartsWith(value,  
                StringComparison.CurrentCultureIgnoreCase)); 
        foreach (string line in command) { 
            string vals = line 
                .Replace("@nick", nick) 
                .Replace("@upnick", nick.ToUpper()) 
                .Replace(value + " ", ""); 
            return vals; 
        } 
        return null; 
    } 

所以我已经尝试了几个小时,我环顾四周,找不到任何与我正在尝试做的事情相关的东西。

我正在阅读一个名为“commands.txt”的文本文件,我正在尝试解析该文本。内容如下:

!help Hello, current commands are: !help, !ver
!ver Testing this

现在如果我拉

string x1 = File.ReadAllLines("commands.txt").ToString(); 
string[] x2 = x1.Split(' '); 
string x3 = x2[0]; 
Console.WriteLine(x3); 

我得到“索引超出数组范围”。我不知道我做错了什么。我还尝试使用“静态 bool ”来调用命令是否存在,到目前为止我得到了

public static bool CommandExists(String value) 
{ 
    if (File.ReadAllLines("commands.txt").Contains(value.ToString())) { 
        return true; 
    } 
    else 
    {  
        return false;  
    } 
} 

但效果不佳。

是什么导致了这个异常?

编辑:CommandParse()

    public static string CommandParse(string value, string nick) 
    { 
        string[] commands = File.ReadAllText("commands.txt") 
               .Split() 
               .Where(x => x.StartsWith("!"+value.ToLower())) 
               .Distinct() 
               .ToArray(); 
        string cmd = commands[1] 
            .Replace("@nick", nick) 
            .Replace("@nickup", nick.ToUpper()); 
        return cmd; 
    } 

现在我知道返回 True,我如何让它不返回 true,而是返回命令本身

请您参考如下方法:

ReadAllLines 返回一个字符串数组,您正在使用 ToString 而不是获取行,而是获取不包含任何 while 的字符串数组的类型名称-space 所以 Split(' ') 不会改变任何东西。如果你想阅读所有文本,请使用 ReadAllText 方法。

string x1 = File.ReadAllText("commands.txt"); 

似乎所有命令都以 ! 开头,因此您可以将所有命令放入数组中,如下所示:

string[] commands = File.ReadAllText("commands.txt") 
                   .Split() 
                   .Where(x => x.StartsWith("!")) 
                   .Distinct() 
                   .ToArray(); 

那么您的方法将如下所示:

public static bool CommandExists(String value) 
{ 
    string[] commands = File.ReadAllText("commands.txt") 
                   .Split() 
                   .Where(x => x.StartsWith("!")) 
                   .Distinct() 
                   .ToArray(); 
 
    return commands.Contains(value); 
} 

如果您想排除开头的!,请添加.Select(x => x.TrimStart('!'))在 Where 之后。