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

后端 未结 12 2319
-上瘾入骨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 15:00

    How About this..

    string str = "The quick brown fox jumps over the lazy dog,";
    StringBuilder sb = new StringBuilder(str);
    sb.Remove(str.Length - 1, 1);
    
    0 讨论(0)
  • 2020-12-23 15:04

    I recommend, you change your loop algorithm:

    • Add the comma not AFTER the item, but BEFORE
    • Use a boolean variable, that starts with false, do suppress the first comma
    • Set this boolean variable to true after testing it
    0 讨论(0)
  • 2020-12-23 15:04

    You should use the string.Join method to turn a collection of items into a comma delimited string. It will ensure that there is no leading or trailing comma, as well as ensure the string is constructed efficiently (without unnecessary intermediate strings).

    0 讨论(0)
  • 2020-12-23 15:05

    I prefer manipulating the length of the stringbuilder:

    data.Length = data.Length - 1;
    
    0 讨论(0)
  • 2020-12-23 15:05

    Yes, convert it to a string once the loop is done:

    String str = data.ToString().TrimEnd(',');
    
    0 讨论(0)
  • 2020-12-23 15:06

    Use the following after the loop.

    .TrimEnd(',')
    

    or simply change to

    string commaSeparatedList = input.Aggregate((a, x) => a + ", " + x)
    
    0 讨论(0)
提交回复
热议问题