Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to fmt.Print("print this on the center")

Tags:

go

Is possible, with fmt.Println("...") to print a string with center alignement of the shell?

like image 805
sensorario Avatar asked Dec 14 '16 00:12

sensorario


2 Answers

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.

like image 121
PaSTE Avatar answered Oct 08 '22 18:10

PaSTE


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

like image 21
miltonb Avatar answered Oct 08 '22 18:10

miltonb