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
+6k Golang : Get environment variable
+12.1k Golang : Generate Code128 barcode
+4.8k Unix/Linux : How to open tar.gz file ?
+7.5k Golang : How to join strings?
+12.3k Golang : Get dimension(width and height) of image file
+7.1k Golang : Oanda bot with Telegram and RSI example
+10.9k Golang : Flush and close file created by os.Create and bufio.NewWriter example
+6.1k Golang : Accessing dataframe-go element by row, column and name example
+20.8k Golang : Securing password with salt
+9.1k Golang : Text file editor (accept input from screen and save to file)
+6k Golang : Fibonacci number generator examples
+12.5k Golang : Check if an integer is negative or positive