Commit a627d61d authored by Stephen Ma's avatar Stephen Ma Committed by Rob Pike

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
parent fe746055
...@@ -86,6 +86,7 @@ var fmttests = []fmtTest{ ...@@ -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"},
......
...@@ -7,6 +7,7 @@ package fmt ...@@ -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) { ...@@ -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)
......
...@@ -43,7 +43,9 @@ ...@@ -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
......
Markdown is supported
0%
or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment