2

I have a string which i have initialized to empty and building the string as seen below i have also got the preferred output i would like, whats the best mathod of doing this as this would be sent as an email. tak into account company names will be off different length.

string being buit

foreach(string s in array)
{
emailBody += s + "          Success" + Environment.NewLine;
}

Ouput of String

CompanyName    Success
CompanyName       Success
CompanyName         Success
CompanyName           Success
CompanyName         Success
CompanyName            Success
CompanyName          Success

Would like output like below


CompanyName   |   Success
CompanyName   |   Success
CompanyName   |   Success
CompanyName   |   Success
CompanyName   |   Success
CompanyName   |   Success
CompanyName   |   Success

Output of Solution given

qxeawgentina                                           Success
TweseqmeChile                                           Success
Vidqwedal                                           Success
qwebr                                           Success
Doqa_brasil                                           Success
Sedaqqagentina                                           Success
KnaqwertArtina                                           Success
Simon Patel
  • 131
  • 2
  • 7

3 Answers3

4

PadLeft is a nice function to use for stuff like this. You could do something like this:

StringBuilder myString = new StringBuilder();
foreach(string s in array)
{
    myString.Append(s + "Success".PadLeft(15 - s.Length) + Environment.NewLine);
}
emailBody = myString.ToString();

Change the constant 15 to be the longest CompanyName you have in your collection, otherwise PadLeft will throw an exception when it becomes negative.

(Also StringBuilder is a good idea here as mentioned in the comments)

Kevin DiTraglia
  • 25,746
  • 19
  • 92
  • 138
2

Have a look at this StackOverflow Question

Basically you can use string.Format and specify widths per placeholder, like so:

// Prints "--123       --"
string.Format("--{0,-10}--", 123);
// Prints "--       123--"
string.Format("--{0,10}--", 123);

Edit: Applying this to your example:

foreach(string s in array)
{
    emailBody += string.Format("{0, 25} | Success", s) + Environment.NewLine;
}
Community
  • 1
  • 1
Moeri
  • 9,104
  • 5
  • 43
  • 56
0

Trim your string and calculate the longest string length:

int maxLength = 0;

foreach(string s in array)
{
    l = s.Trim().Length;
    if (l > maxLength)
    {
        maxLength = l;
    }
}

foreach(string s in array)
{
    emailBody += System.Format("{0,-" + maxLength.ToString() + "}    |    Success" + Environment.NewLine, s.Trim());
}
konsolebox
  • 72,135
  • 12
  • 99
  • 105