Oktatás * Programozás 2 * Szkriptnyelvek * levelezősök Félévek Linkek * kalendárium |
CSharp /
20180406aCenter a textIn the terminal you want to center a text in a field of a given width. In Python: >>> s = "hello" >>> s.center(20) ' hello ' >>> s.center(20, '.') '.......hello........' >>> In C# I didn't find such a method so I wrote it as a custom extension. Here is how to use it: csharp> var s = "hello" csharp> s.Center(20) " hello " csharp> s.Center(20, '.') ".......hello........" csharp> Implementation: // center a string in a field of given width (like Python's str.center()) public static string Center(this string s, int width, char fillChar=' ') { var leftMarginWidth = (width - s.Length) / 2; if (leftMarginWidth < 0) { leftMarginWidth = 0; } var rightMarginWidth = width - s.Length - leftMarginWidth; if (rightMarginWidth < 0) { rightMarginWidth = 0; } return string.Format("{0}{1}{2}", new string(fillChar, leftMarginWidth), s, new string(fillChar, rightMarginWidth)); } Some tests: [Fact] public void Center() { Assert.Equal(" * ", "*".Center(10)); Assert.Equal("....*.....", "*".Center(10, '.')); Assert.Equal("....**....", "**".Center(10, '.')); Assert.Equal("...***....", "***".Center(10, '.')); Assert.Equal("**********", "**********".Center(10, '.')); Assert.Equal("***********", "***********".Center(10, '.')); Assert.Equal(".hello..", "hello".Center(8, '.')); } See the current version here. |
Blogjaim, hobbi projektjeim * The Ubuntu Incident [ edit ] |