agenis
agenis

Reputation: 8377

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).

Upvotes: 2

Views: 1615

Answers (3)

Jeremy Feng
Jeremy Feng

Reputation: 365

I want to print a string with centering align and padding with #.

stringr::str_pad("hello", 20, side = "both", pad = "#")

It will output:

[1] "#######hello########"

Upvotes: 1

agenis
agenis

Reputation: 8377

Eventually, I know it's not the same language, but it is Worth noting that Python (and not R) has a built-in method for doing just that, it's called centering a string:

example = "John"
example.center(10)
#### '   john   '

It adds to the right for odd Numbers, and allows you to input the filling character of your choice. ALthough it's not vectorized.

Upvotes: 0

Rich Scriven
Rich Scriven

Reputation: 99331

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")

Upvotes: 6

Related Questions