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

时间:2018-12-03 14:39:32

标签: c# string trim

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

  

System.ArgumentOutOfRangeException:'StartIndex不能小于零。

该字符串可以很好地写入文件,但是在出现上述错误时会中断。我不确定为什么会这样,任何建议都将不胜感激。

我使用的代码如下

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();
}

5 个答案:

答案 0 :(得分:6)

循环添加string

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

不是是个好主意。输入Join

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

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

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

答案 1 :(得分:5)

尝试string.TrimEnd()

writeUnEditedData = writeUnEditedData.TrimEnd(',');

答案 2 :(得分:2)

在执行删除操作之前,添加检查以查看writeUnEditedData是否不是空字符串。空字符串将导致Remove(-1),我认为这会引发StartIndex不能小于0的错误。

答案 3 :(得分:1)

这通常意味着字符串为空。

尝试将此保护代码放入:

string writeData = string.IsNullOrEmpty(writeUnEditedData)
    ? string.Empty
    : writeUnEditedData.Remove(writeUnEditedData.Length - 1);

答案 4 :(得分:1)

您可以改进此模式:

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

为避免首先添加逗号:

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

或带有StringBuilder的...虽然与流行的看法相反,但这仅在connectionData集合很大的情况下才有帮助:

string delimiter = "";
var writeUnEditedData = new StringBuilder();        
foreach (int s in connectionData)
{
    writeUnEditedData.Append(delimiter).Append(s);
    delimiter = ",";
}

更好的是,流式传输整个内容,以避免需要所有额外的内存和处理:

string fileName2 = @"D:\UNI\Year 5\AI - SET09122\SET09122 - CW1\WriteConnectionData.txt";
using (var sw = new StreamWriter(fileName2, true))
{
    for (int z = 0; z <= totalNumberOfCaves; z++)
    {
        string delimiter = "";
        for (int i = 0; i < totalNumberOfCaves && connectionStack.Count > 0; i++)
        {
            sw.Write(delimiter);
            sw.Write(connectionStack.Pop());
            delimiter = ",";
        }
        sw.Write(Environment.NewLine);
    }
}