Best way to remove the last character from a string built with stringbuilder

后端 未结 12 2404
-上瘾入骨i
-上瘾入骨i 2020-12-23 14:30

I have the following

data.AppendFormat(\"{0},\",dataToAppend);

The problem with this is that I am using it in a loop and there will be a t

12条回答
  •  别那么骄傲
    2020-12-23 14:41

    Gotcha!!

    Most of the answers on this thread won't work if you use AppendLine like below:

    var builder = new StringBuilder();
    builder.AppendLine("One,");
    builder.Length--; // Won't work
    Console.Write(builder.ToString());
    
    builder = new StringBuilder();
    builder.AppendLine("One,");
    builder.Length += -1; // Won't work
    Console.Write(builder.ToString());
    
    builder = new StringBuilder();
    builder.AppendLine("One,");
    Console.Write(builder.TrimEnd(',')); // Won't work
    

    Fiddle Me

    WHY??? @(&**(&@!!

    The issue is simple but took me a while to figure it out: Because there are 2 more invisible characters at the end CR and LF (Carriage Return and Line Feed). Therefore, you need to take away 3 last characters:

    var builder = new StringBuilder();
    builder.AppendLine("One,");
    builder.Length -= 3; // This will work
    Console.WriteLine(builder.ToString());
    

    In Conclusion

    Use Length-- or Length -= 1 if the last method you called was Append. Use Length =- 3 if you the last method you called AppendLine.

提交回复
热议问题