Recent Changes - Search:

Oktatás

* Programozás 1
  + feladatsor
  + GitHub oldal

* Szkriptnyelvek
  + feladatsor
  + quick link

Teaching

* Programming 1 (BI)
  ◇ exercises
  ◇ quick link

* Scripting Languages
  ◇ exercises
  ◇ quick link

teaching assets


Félévek

* aktuális (2023/24/2)
* archívum


Linkek

* kalendárium
   - munkaszüneti napok '20
* tételsorok
* jegyzetek
* szakdolgozat / PhD
* ösztöndíjak
* certificates
* C lang.
* C++
* C#
* Clojure
* D lang.
* Java
* Nim
* Scala


[ edit | logout ]
[ sandbox | passwd ]

20180406a

Center a text

In 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.

Cloud City

  

Blogjaim, hobbi projektjeim

* The Ubuntu Incident
* Python Adventures
* @GitHub
* heroku
* extra
* haladó Python
* YouTube listák


Debrecen | la France


[ edit ]

Edit - History - Print *** Report - Recent Changes - Search
Page last modified on 2018 April 07, 23:50