Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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..

like image 811
eMi Avatar asked Feb 08 '12 10:02

eMi


4 Answers

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 ); .

like image 109
Yahia Avatar answered Sep 18 '22 05:09

Yahia


I think you are confusing with tab char and sapces.

Are you expecting fixed no of white spaces to be added in the end of every word?

\t -> is just a tab char

The following is generated by the code given by you.

Java    StackOverflow   Banyan
Javasun StackOverflow   Banyan

The above two lines have same tab char b/w the 1st & 2nd Word.

if you type one more char in the end of "Javasun" it will extend like the following

Javaasunk   StackOverflow   Banyan
like image 32
Prakash P Avatar answered Sep 18 '22 05:09

Prakash P


I would have thought you would want

StringBuilder stringBuilder = new StringBuilder();
foreach (string field in fields)
{
    stringBuilder.Append(field);
    stringBuilder.Append("\t");
}
stringBuilder.AppendLine();
return stringBuilder.ToString();
like image 37
ColWhi Avatar answered Sep 18 '22 05:09

ColWhi


Instead of looping, you can use string.Join:

StringBuilder stringBuilder = new StringBuilder();

stringBuilder.AppendLine(string.Join("\t", fields));

Note that you can pass in the string directly to AppendLine as well.

like image 44
Oded Avatar answered Sep 17 '22 05:09

Oded