gpt4 book ai didi

go - 如何 fmt.Print ("print this on the center")

转载 作者:IT王子 更新时间:2023-10-29 00:53:33 27 4
gpt4 key购买 nike

是否有可能使用 fmt.Println("...") 打印一个 shell 居中对齐的字符串?

最佳答案

作为对这个长期回答问题的更新,可以通过使用 fmt 包中的 * 符号来改进@miltonb 发布的解决方案。来自 the package documentation :

In Printf, Sprintf, and Fprintf, the default behavior is for eachformatting verb to format successive arguments passed in the call.However, the notation [n] immediately before the verb indicates thatthe nth one-indexed argument is to be formatted instead. The samenotation before a '*' for a width or precision selects the argumentindex holding the value. After processing a bracketed expression [n],subsequent verbs will use arguments n+1, n+2, etc. unless otherwisedirected.

所以你可以用更简洁的格式语句替换两个 fmt.Sprintf 调用来获得相同的结果:

s := "in the middle"
w := 110 // or whatever

fmt.Sprintf("%[1]*s", -w, fmt.Sprintf("%[1]*s", (w + len(s))/2, s))

See the code in action .

此外,正如@chris-dennis 提到的,[1] 表示法在此示例中是多余的,因为字符串的宽度已经是第一个参数。这也适用:

fmt.Sprintf("%*s", -w, fmt.Sprintf("%*s", (w + len(s))/2, s))

See this example in action .

关于go - 如何 fmt.Print ("print this on the center"),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41133006/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com