Is possible, with fmt.Println("...")
to print a string with center alignement of the shell?
As an update to this long-answered question, the solution posted by @miltonb can be improved upon by using the *
notation from the fmt
package. From the package documentation:
In Printf, Sprintf, and Fprintf, the default behavior is for each formatting verb to format successive arguments passed in the call. However, the notation [n] immediately before the verb indicates that the nth one-indexed argument is to be formatted instead. The same notation before a '*' for a width or precision selects the argument index holding the value. After processing a bracketed expression [n], subsequent verbs will use arguments n+1, n+2, etc. unless otherwise directed.
So you can replace two of the fmt.Sprintf
calls with a more concise format statement to achieve the same result:
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.
Additionally, as @chris-dennis mentioned, the [1]
notation is superfluous in this example because the width of the string is already the first argument. This works as well:
fmt.Sprintf("%*s", -w, fmt.Sprintf("%*s", (w + len(s))/2, s))
See this example in action.
This code is managing to centre the text as long as the shell width is a known value. Its not quite 'pixel perfect', but I hope it helps.
If we break it down there are two bits of code to produce the format strings to pad right and then left.
fmt.Sprintf("%%-%ds", w/2) // produces "%-55s" which is pad left string
fmt.Sprintf("%%%ds", w/2) // produces "%55s" which is right pad
So the final Printf
statement becomes
fmt.Printf("%-55s", fmt.Sprintf("%55s", "my string to centre"))
The full code:
s := " in the middle"
w := 110 // shell width
fmt.Printf(fmt.Sprintf("%%-%ds", w/2), fmt.Sprintf(fmt.Sprintf("%%%ds", w/2),s))
Produces the following:
in the middle
Link to play ground: play
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With