1
0
mirror of https://github.com/golang/go synced 2024-11-25 05:57:57 -07:00

Count utf8 runes, not bytes when determining string width. Note

that pad() still counts bytes, but it's currently only used for
1 byte runes.

Fixes #612.

R=r
CC=golang-dev
https://golang.org/cl/217064
This commit is contained in:
Stephen Ma 2010-02-28 21:15:56 +11:00 committed by Rob Pike
parent fe746055a2
commit a627d61d5d
3 changed files with 6 additions and 2 deletions

View File

@ -86,6 +86,7 @@ var fmttests = []fmtTest{
// width // width
fmtTest{"%5s", "abc", " abc"}, fmtTest{"%5s", "abc", " abc"},
fmtTest{"%2s", "\u263a", " \u263a"},
fmtTest{"%-5s", "abc", "abc "}, fmtTest{"%-5s", "abc", "abc "},
fmtTest{"%05s", "abc", "00abc"}, fmtTest{"%05s", "abc", "00abc"},

View File

@ -7,6 +7,7 @@ package fmt
import ( import (
"bytes" "bytes"
"strconv" "strconv"
"utf8"
) )
const ( const (
@ -127,7 +128,7 @@ func (f *fmt) padString(s string) {
var padding []byte var padding []byte
var left, right int var left, right int
if f.widPresent && f.wid != 0 { if f.widPresent && f.wid != 0 {
padding, left, right = f.computePadding(len(s)) padding, left, right = f.computePadding(utf8.RuneCountInString(s))
} }
if left > 0 { if left > 0 {
f.writePadding(left, padding) f.writePadding(left, padding)

View File

@ -43,7 +43,9 @@
For numeric values, the width and precision flags control For numeric values, the width and precision flags control
formatting; width sets the width of the field, precision the formatting; width sets the width of the field, precision the
number of places after the decimal, if appropriate. The number of places after the decimal, if appropriate. The
format %6.2f prints 123.45. format %6.2f prints 123.45. The width of a field is the number
of Unicode code points in the string. This differs from C's printf where
the field width is the number of bytes.
Other flags: Other flags:
+ always print a sign for numeric values + always print a sign for numeric values