文字列のセンタリング
Posted feedbacks - diff
substr()二度もやるのは無駄じゃん。
Dan the Lazier
1 2 3 4 5 6 7 8 9 10 | --- center.pl.orig 2007-11-17 04:35:53.000000000 +0900
+++ center.pl 2007-11-17 05:17:39.000000000 +0900
@@ -8,8 +8,7 @@
my $margin = int(($width - length($str))/2);
return $str if $margin == 0;
return " " x int($margin) . $str if $margin > 0;
- substr($str, 0, -$margin, '');
- return substr($str, 0, $width);
+ return substr($str, -$margin, $width);
}
|
String#centerは右側からパディングを入れるようですので,それにあわせて,widthをはみ出す場合は「左側から削る」ようにしました.
Rubyでは,(CやPerlと異なり)負の整数の除算の場合,剰余の符号が除数(divisor)の符号と一致するような商が得られますが,4行目で文字列を削る際にその性質を利用しています. (4171 を見てぱくりました.勉強になります:-)
p "0123456789".centered(3) # "456" p "012".centered(5) # " 012 " p "012".centered(4) # "012 " p "012".centered(3) # "012" p "012".centered(2) # "12" p "012".centered(1) # "1" p "012".centered(0) # "" p "012".centered(-1) # "012" p "012".center(4) == " 012 ".centered(4) # true
1 2 3 4 5 6 7 8 9 10 11 | --- center.rb.orig 2007-11-19 17:17:47.000000000 +0900
+++ center.rb 2007-11-19 17:17:39.000000000 +0900
@@ -1,7 +1,7 @@
class String
def centered(width = 80)
- return center(width) if width > size
- self[(size - width) / 2, width]
+ return center(width) if width > size or 0 > width
+ self[-((width - size) / 2), width]
end
end
|




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