Search code examples
c#stringtabsappendstringbuilder

StringBuilder, add Tab between Values


I have a small problem:

I have a List of fields, with 3 Values. I want to build my String with these three Values, delimited by a "TAB"..

Code:

StringBuilder stringBuilder = new StringBuilder();
foreach (string field in fields)
{
    stringBuilder.Append(field).Append("\t");
}
stringBuilder.AppendLine();
return stringBuilder.ToString();

The Tab is only between the 3rd and 2nd Value (Between 1st and 2nd is a Space ?!)

So I tried this:

StringBuilder stringBuilder = new StringBuilder();
foreach (string field in fields)
{
    stringBuilder.Append(field + "\t").Append("\t");
}
stringBuilder.AppendLine();
return stringBuilder.ToString();

Then I have 2 Tabs between 3rd and 2nd, one Tab between 1st and 2nd and also a Space between 1st and 2nd..

(The Space is always there, how to avoid that?)

So what I have to do? Need only (without spaces..) a Tab between these Values..


Solution

  • try

    StringBuilder stringBuilder = new StringBuilder();
    foreach (string field in fields)
    {
        stringBuilder.Append(field.Trim()).Append("\t");
    }
    stringBuilder.AppendLine();
    return stringBuilder.ToString();
    

    Basically I would just use return string.Join ( "\t", fields ); .