Created
September 28, 2016 11:49
-
-
Save athurg/2cbf3624ec013761b1046e0e09ad7ea2 to your computer and use it in GitHub Desktop.
非ASCII字符串对其输出代码
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"fmt" | |
"strings" | |
"unicode/utf8" | |
) | |
func main() { | |
a := "中文A是不是很长啊对的很" | |
b := "ZWA.ABC.ABC" | |
fmt.Printf("|%s|\n", padString(a, 24)) | |
fmt.Printf("|%s|\n", padString(b, 24)) | |
fmt.Printf("|%s|\n", padString(b, -24)) | |
fmt.Printf("|%s|\n", strings.Replace(a, "", "", 24)) | |
fmt.Printf("|%s|\n", strings.Replace(b, "", "", 24)) | |
} | |
//调整字符串宽度,不足部分填空格,非ASCII算两个字符 | |
func padString(str string, length int) string { | |
var padLeft bool | |
if length < 0 { | |
padLeft = true | |
length *= -1 | |
} | |
runeCount := utf8.RuneCountInString(str) | |
if runeCount == 0 || runeCount >= length { | |
return str | |
} | |
length -= runeCount | |
length -= (len(str) - runeCount) / 2 | |
//左 | |
if length <= 0 { | |
return str | |
} else if padLeft { | |
return str + strings.Repeat(" ", length) | |
} else { | |
return strings.Repeat(" ", length) + str | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment