Golang : Aligning strings to right, left and center with fill example
Problem:
You are so used to Python way of aligning text strings such as ljust()
, rjust()
and center()
and Golang's text/tabwriter
is not what you are looking for. So how to align text strings in Golang?
Solution:
Write your own functions with help from strings.Repeat()
function. For example:
package main
import (
"fmt"
"strings"
)
func rightjust(s string, n int, fill string) string {
return strings.Repeat(fill, n) + s
}
func leftjust(s string, n int, fill string) string {
return s + strings.Repeat(fill, n)
}
func center(s string, n int, fill string) string {
div := n / 2
return strings.Repeat(fill, div) + s + strings.Repeat(fill, div)
}
func main() {
str := "Hello World!"
fmt.Println("Original : ", str)
fmt.Println("Adjust 20 spaces right : [" + rightjust(str, 20, " ") + "]")
fmt.Println("Adjust 20 spaces left : [" + leftjust(str, 20, " ") + "]")
fmt.Println("Center 10 spaces : [" + center(str, 20, " ") + "]")
fmt.Println("Center * fill : [" + center(str, 10, "*") + "]")
}
References:
See also : Golang : concatenate(combine) strings
By Adam Ng
IF you gain some knowledge or the information here solved your programming problem. Please consider donating to the less fortunate or some charities that you like. Apart from donation, planting trees, volunteering or reducing your carbon footprint will be great too.
Advertisement
Tutorials
+5.7k Golang : Example of how to detect which type of script a word belongs to
+10.9k Golang : Pass database connection to function called from another package and HTTP Handler
+7.2k Golang : Gorilla web tool kit schema example
+13.1k Golang : Basic authentication with .htpasswd file
+4.1k Golang : Shortening import identifier
+6.9k Golang : Implementing class(object-oriented programming style)
+17.3k Golang : Check if directory exist and create if does not exist
+4.8k Golang : Handling image beyond OpenCV video capture boundary
+17.1k Golang : Compare floating-point numbers
+6.7k Golang : Emulate NumPy way of creating matrix example
+9.6k Golang : Find and draw contours with OpenCV example
+19.6k Golang : Use TLS version 1.2 and enforce server security configuration over client