Last active
July 3, 2024 21:11
-
-
Save hartfordfive/69f84657267c2327e484 to your computer and use it in GitHub Desktop.
Go function to center a string with whitespace padding
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| package main | |
| import ( | |
| "bytes" | |
| "fmt" | |
| ) | |
| // Example: http://play.golang.org/p/Q34HEmWMXh | |
| func main() { | |
| fmt.Printf("|%s|%s|%s|%s|\n", | |
| centerString("First Name", 20), | |
| centerString("Last Name", 20), | |
| centerString("DOB", 20), | |
| centerString("Country", 22)) | |
| fmt.Println("----------------------------------------------------------------------------------------") | |
| fmt.Printf("|%s|%s|%s|%s|\n", | |
| centerString("John", 20), | |
| centerString("Doe", 20), | |
| centerString("July 15, 1975", 20), | |
| centerString("United States", 22)) | |
| } | |
| func centerString(str string, total_field_width int) string { | |
| str_len := len(str) | |
| spaces_to_pad := total_field_width - str_len | |
| var tmp_spaces float64 | |
| var lr_spaces int | |
| tmp_spaces = float64(spaces_to_pad) / 2 | |
| lr_spaces = int(tmp_spaces) | |
| buffer := bytes.NewBufferString("") | |
| spaces_remaining := total_field_width | |
| for i := 0; i < lr_spaces; i++ { | |
| buffer.WriteString(" ") | |
| spaces_remaining = spaces_remaining - 1 | |
| } | |
| buffer.WriteString(str) | |
| spaces_remaining = spaces_remaining - str_len | |
| for i := spaces_remaining; i > 0; i-- { | |
| buffer.WriteString(" ") | |
| } | |
| return buffer.String() | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
I initially thought @tanema 's solution would be slower, but then I checked it and it's actually much faster for "medium" widths, though a bit slower for very small ones!
I came up with a solution that works using just a format string, but that's a bit slower as well:
As I will use this function on a logger handler, I wanted it to be fast... also, I was just curious, so I wrote a quick benchmark:
Results on my Macbook Air: