challenge 文字列のセンタリング

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

Posted feedbacks - Io

Io で普通に書いてみました。alignCenter があるのできりつめるところだけです。

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
Sequence centered := method(width,
    margin := (width - self size) / 2
    if (margin < 0,
        self slice(-margin, self size + margin)
    ,
        self alignCenter(width)
    )
)


# なんか手元のだと定義されていないので
Number to := method(i,
    Range clone setRange(self, i)
)

0 to(7) foreach(i,
    "proto" asMutable centered(i) justSerialized
    "" println
)

/* output

""
"o"
"ro"
"rot"
"prot"
"proto"
"proto "
" proto "

*/

Index

Feed

Other

Link

Pathtraq

loading...