gpt4 book ai didi

c# - 尝试删除字符串的最后一个字符时出错

转载 作者:行者123 更新时间:2023-11-30 18:56:09 25 4
gpt4 key购买 nike

我正在尝试删除字符串的最后一个 "," 但是我收到一条错误消息

System.ArgumentOutOfRangeException: 'StartIndex cannot be less than zero.

字符串写入文件正常,但在运行时出现上述错误时中断。我不确定为什么会这样,如有任何建议,我们将不胜感激。

我使用的代码如下

for (int z = 0; z <= totalNumberOfCaves; z++)
{
for (int i = 0; i < totalNumberOfCaves && connectionStack.Count > 0; i++)
{
connectionData.Add(int.Parse(connectionStack.Pop()));
}
string fileName2 = @"D:\UNI\Year 5\AI - SET09122\SET09122 - CW1\WriteConnectionData.txt";
string writeUnEditedData = "";
foreach (int s in connectionData)
{
writeUnEditedData += (s + ",");
}
using (StreamWriter sw = File.AppendText(fileName2))
{
string writeData = writeUnEditedData.Remove(writeUnEditedData.Length - 1);
sw.Write("{ " + writeData + " }," + Environment.NewLine);
}
connectionData.Clear();
}

最佳答案

在循环中追加 string:

    foreach (int s in connectionData)
{
writeUnEditedData += (s + ",");
}

不是一个好主意。将 加入:

    writeUnEditedData = string.Join(",", connectionData); 

完成此操作后,您无需删除任何内容:

 using (StreamWriter sw = File.AppendText(fileName2))
{
// No Remove here
string writeData = writeUnEditedData;
...

关于c# - 尝试删除字符串的最后一个字符时出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53596009/

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