In Golang, you can use the Strings
package to pad a string with a specific character to a specified length. The Repeat
function can be used to repeat a character a certain number of times, and the Len
function can be used to get the length of a string.
Here's an example of how you can pad a string with a specific character to a specified length:
package main
import (
"fmt"
"strings"
)
func PadString(s string, padChar rune, length int) string {
if length <= len(s) {
return s
}
padLength := length - len(s)
pad := strings.Repeat(string(padChar), padLength)
return s + pad
}
func main() {
s := "hello"
padded := PadString(s, '-', 10)
fmt.Println(padded)
}
In this example, the PadString
function takes three arguments: the original string s
, the character to pad with padChar
, and the desired length length
. It calculates the pad length by subtracting the length of the original string from the desired length. Then, using the Repeat
function from the Strings
package, it repeats the padChar
a certain number of times to create the padding. Finally, it concatenates the original string with the padding and returns the padded string.
In the main
function, we test the PadString
function by padding the string "hello" with hyphens ("-") to a length of 10. The output would be "hello-----".