Reputation: 141
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
Upvotes: 3
Views: 1174
Reputation: 75488
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());
}
Upvotes: 0
Reputation: 26058
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)
Upvotes: 5
Reputation: 9294
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;
}
Upvotes: 2