center a string by padding spaces up to a specified length

风流意气都作罢 提交于 2019-12-06 08:29:57

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

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!