c# - Pad Left & Pad Right (Pad Center) String -


string has both padleft , padright. in need of padding both left , right (center justification). there standardized way of doing this, or better yet, built in way of achieving same goal?

not know of. can create extension method if see using lot. assuming want string end in center, use following

public string padboth(string source, int length) {     int spaces = length - source.length;     int padleft = spaces/2 + source.length;     return source.padleft(padleft).padright(length);  } 

to make extension method, so:

namespace system {     public static class stringextensions     {         public static string padboth(this string str, int length)         {             int spaces = length - str.length;             int padleft = spaces / 2 + str.length;             return str.padleft(padleft).padright(length);         }     } } 

as aside, include extensions in system namespace - it's do.


Comments