Skip to contents

Pad a string to a minimum length

Usage

str_pad(
  strings,
  min_length = max(nchar(strings)) + 1,
  side = c("left", "right", "both"),
  pad = " ",
  prefer_side = c("right", "left")
)

Arguments

strings

A character vector, where each element of the vector is a character string.

min_length

The minimum number of characters in the padded string. The default is one more character than the longest string in strings. Strings already longer than min_length will be unchanged.

side

Which side of the string should the indent be applied, one of "left", "right" or "both". The left side is the default. When "both", half the required padding length with be added to each side, with prefer_side controlling where odd additions go.

pad

A single character used to pad the space

prefer_side

If side is "both", which side should get one extra pad when min_length is odd? Default to the right side.

Value

A character vector equal in length to strings, with each string having at least as many characters as min_length. Strings already longer than min_length

will be unchanged.

See also

str_indent() for adding a specific number of characters.

str_concat() and str_glue() for combining strings together.

Base paste0() and strrep() used by this function.

Examples

str_pad(c("Hello", "World"))
#> [1] " Hello" " World"

str_pad(c("Hello", "World"), 10)
#> [1] "     Hello" "     World"

str_pad(c("Hello", "World"),
        10,
        side = "both")
#> [1] "  Hello   " "  World   "

str_pad(c("Hello", "World"),
        10,
        side = "both",
        pad = ".")
#> [1] "..Hello..." "..World..."

str_pad(c("Hello", "World"),
        10,
        side = "both",
        pad = ".",
        prefer_side = "left")
#> [1] "...Hello.." "...World.."