Skip to content

Instantly share code, notes, and snippets.

@asessa
Created September 6, 2016 22:48
Show Gist options
  • Save asessa/3aaec43d93044fc42b7c6d5f728cb039 to your computer and use it in GitHub Desktop.
Save asessa/3aaec43d93044fc42b7c6d5f728cb039 to your computer and use it in GitHub Desktop.
golang padding strings
package util
import (
"math"
"strings"
)
// StrPad returns the input string padded on the left, right or both sides using padType to the specified padding length padLength.
//
// Example:
// input := "Codes";
// StrPad(input, 10, " ", "RIGHT") // produces "Codes "
// StrPad(input, 10, "-=", "LEFT") // produces "=-=-=Codes"
// StrPad(input, 10, "_", "BOTH") // produces "__Codes___"
// StrPad(input, 6, "___", "RIGHT") // produces "Codes_"
// StrPad(input, 3, "*", "RIGHT") // produces "Codes"
func StrPad(input string, padLength int, padString string, padType string) string {
var output string
inputLength := len(input)
padStringLength := len(padString)
if inputLength >= padLength {
return input
}
repeat := math.Ceil(float64(1) + (float64(padLength-padStringLength))/float64(padStringLength))
switch padType {
case "RIGHT":
output = input + strings.Repeat(padString, int(repeat))
output = output[:padLength]
case "LEFT":
output = strings.Repeat(padString, int(repeat)) + input
output = output[len(output)-padLength:]
case "BOTH":
length := (float64(padLength - inputLength)) / float64(2)
repeat = math.Ceil(length / float64(padStringLength))
output = strings.Repeat(padString, int(repeat))[:int(math.Floor(float64(length)))] + input + strings.Repeat(padString, int(repeat))[:int(math.Ceil(float64(length)))]
}
return output
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment