gpt4 book ai didi

c# - 如何更改 C# 文本文件中的未知数字?

转载 作者:太空宇宙 更新时间:2023-11-03 22:54:37 24 4
gpt4 key购买 nike

我正在尝试为我的 Discord 服务器的机器人创建一个“警告系统”,当使用命令时,它会从文本文件中提取信息,然后更新它。我可以逐步设想我想要发生的事情,但我对如何从文件中提取要读取的内容感到困惑:

鲍勃#5368 3
标记#8459 6
辛迪#1254 2

我只想更改名称后面的数字,我不太确定如何基本上找到我要查找的用户,然后拉出数字并将其设置为“totalWarn”,将其相加( totalWarn =+ warnNum),然后用新号码更新该用户。

注意:'warningFile' 是已在此代码块之外定义的文件路径。

public async Task warn(IGuildUser user, int warnNum, [Remainder] string reason)
{
int totalWarn = 0;
if (user == null)
await ReplyAsync("Please include a name");
if (warnNum <= 0)
await ReplyAsync("The warning level must increase by 1 or more.");
if (reason == null)
await ReplyAsync("Please include a reason.");

string nickName = user.Username;

//Check for whether text file exists or not.
if (!File.Exists(warningFile))
{
//Create the File
FileStream fs = File.Create(warningFile);
}

//Reads all the text in the file and puts it into an array.
string[] arr = File.ReadAllLines(warningFile);
for (int i = 0; i < arr.Length; i++)
{
string line = arr[i];
}



totalWarn = +warnNum;
await Context.Channel.SendMessageAsync($"{user.Username}'s warning level has increased by {warnNum} for {reason}.\n"
+ $"Your warning level is now {totalWarn}. Please take this time to review the server rules.");
}

我不是在找人帮我完成它,只是在我完全迷失方向时帮助自己朝着正确的方向前进,而且关于更改文本的信息也不是很有帮助。

最佳答案

下面是如何使用正则表达式解析文件中的一行:

void Main()
{
string line = "bob#5368 3";
GuildUser user = new GuildUser( line );
user.Warnings++;
user.ToString().Dump();
}

public class GuildUser
{
public string Name { get; set;}
public int Id { get; set;}
public int Warnings { get; set;}
public GuildUser( string line )
{
Match match = Regex.Match( line, @"(.+)?#(\d+) (\d+)" );
if ( !match.Success ) throw new Exception( "Couldn't parse line: " + line );
Name = match.Groups[1].Value;
Id = int.Parse( match.Groups[2].Value );
Warnings = int.Parse( match.Groups[3].Value );

}
public override string ToString()
{
return $"{Name}#{Id} {Warnings}";
}
}

您可以使用 File.ReadAllLines、File.WriteAllLines。

我可能也会使用一些 linq。

我更新以添加“ToString”方法来重写该行。然后,您只需添加警告并获取调用 ToString() 的新字符串。

关于c# - 如何更改 C# 文本文件中的未知数字?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45987152/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com