Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Aligning a string with string.Format()

I got a method which receives a message and a Priority enum and returns a formatted string.

private string FormatMessage(string message, Priority priority)
{
    return string.Format("*{0,-6}* - {1}", priority, message);
}

Priority has three possible values: High, Medium and Low.

I'm using string.Format's alignment option so that the output would look nice. What I'd like the output to look like is this:

*Low*    - First message
*Medium* - Second message
*Low*    - Third message

However, what I'm getting is this:

*Low   * - First message
*Medium* - Second message
*Low   * - Third message

I understand why this is happening, but what I'd like to know is whether there's an easy (and correct) way to get the wanted output by using string.Format and without introducing any new variables.

like image 304
Adi Lester Avatar asked Dec 21 '22 00:12

Adi Lester


1 Answers

string.Format("{0,-8} - {1}", "*" + priority + "*", message);

Or, if you're feeling fancy:

string.Format("{0,-8} - {1}", string.Format("*{0}*", priority), message);
string.Format("{0,-8} - {1}", string.Join(priority, new [] {"*", "*"}), message);
like image 184
Joey Avatar answered Jan 07 '23 06:01

Joey