challenge 文字列のセンタリング

文字列を指定のカラム幅にセンタリング配置する関数を示してください。文字列の長さが指定した幅より長い場合には文字列の両端をできるだけ均等に切り落して指定幅に収めてください。1文字は1カラムに収まるものと仮定してかまいません。

Posted feedbacks - C#

C# だと PadReft っていう指定文字数になるまで空白文字を埋め込むメソッドがあります。
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
using System;
static class Program {
    static void Main() {
        string[] texts = {
            "0123456789",
            "abc",
            "abcdefg",
            "abcdefghijklmn",
        };
        foreach(string text in texts) {
            Console.WriteLine(Centering(text, 10));
        }
    }
    static string Centering(string text, int width) {
        int margin = (int)((width - text.Length) / 2);
        if (margin == 0)
            return text;
        if (0 < margin)
            return text.PadLeft(margin + text.Length);
        return text.Substring(-margin, width);
    }
}

Index

Feed

Other

Link

Pathtraq

loading...