Search code examples
rstringformattingprintfstring-formatting

center a string by padding spaces up to a specified length


I have a vector of names, like this:

x <- c("Marco", "John", "Jonathan")

I need to format it so that the names get centered in 10-character strings, by adding leading and trailing spaces:

> output
# [1] "  Marco   " "   John    " " Jonathan "

I was hoping a solution less complicated than to go with paste, rep, and counting nchar? (maybe with sprintf but I don't know how).


Solution

  • Here's a sprintf() solution that uses a simple helper vector f to determine the low side widths. We can then insert the widths into our format using the * character, taking the ceiling() on the right side to account for an odd number of characters in a name. Since our max character width is at 10, each name that exceeds 10 characters will remain unchanged because we adjust those widths with pmax().

    f <- pmax((10 - nchar(x)) / 2, 0)
    
    sprintf("%-*s%s%*s", f, "", x, ceiling(f), "")
    # [1] "  Marco   "  "   John   "  " Jonathan "  "Christopher"
    

    Data:

    x <- c("Marco", "John", "Jonathan", "Christopher")