Aligning a string with string.Format ()

I have a method that receives a message and Priority enumeration 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 use string.Format alignment parameter to make the result look good. I would like the result to look like this:

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

However, I get the following:

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

I understand why this is happening, but I would like to know if there is a simple (and correct) way to get the desired output using string.Format and without entering any new variables.

+4
source share
2 answers
 string.Format("{0,-8} - {1}", "*" + priority + "*", message); 

Or if you feel like a fantasy:

 string.Format("{0,-8} - {1}", string.Format("*{0}*", priority), message); string.Format("{0,-8} - {1}", string.Join(priority, new [] {"*", "*"}), message); 
+10
source

Could you increase the first column to 8 spaces ?, if so ...

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

Source: https://habr.com/ru/post/1401545/


All Articles