作为对这个长期解答的问题的更新,可以通过使用软件包中的*符号来改进@miltonb发布的解决方案fmt。从包装文件:
在Printf,Sprintf和Fprintf中,默认行为是为每个格式化动词格式化在调用中传递的连续参数。但是,动词前的符号[n]表示将改为格式化第n个单索引参数。宽度或精度的'*'之前的相同符号选择保存该值的参数索引。在处理了带括号的表达式[n]后,除非另外指出,否则后续动词将使用自变量n + 1,n + 2等。
因此,您可以fmt.Sprintf使用更简洁的格式语句替换其中两个调用,以实现相同的结果:
s := "in the middle"
w := 110 // or whatever
fmt.Sprintf("%[1]*s", -w, fmt.Sprintf("%[1]*s", (w + len(s))/2, s))
Run Code Online (Sandbox Code Playgroud)
只要外壳宽度是已知值,此代码就会设法使文本居中。它并不完全“像素完美”,但我希望它能有所帮助。
如果我们分解它,就会有两段代码来生成格式字符串,先向右填充,然后向左填充。
fmt.Sprintf("%%-%ds", w/2) // produces "%-55s" which is pad left string
fmt.Sprintf("%%%ds", w/2) // produces "%55s" which is right pad
Run Code Online (Sandbox Code Playgroud)
所以最后的Printf语句就变成了
fmt.Printf("%-55s", fmt.Sprintf("%55s", "my string to centre"))
Run Code Online (Sandbox Code Playgroud)
完整代码:
s := " in the middle"
w := 110 // shell width
fmt.Printf(fmt.Sprintf("%%-%ds", w/2), fmt.Sprintf(fmt.Sprintf("%%%ds", w/2),s))
Run Code Online (Sandbox Code Playgroud)
产生以下内容:
Run Code Online (Sandbox Code Playgroud)in the middle
操场链接:play
| 归档时间: |
|
| 查看次数: |
1868 次 |
| 最近记录: |