center a string by padding spaces up to a specified length

孤街浪徒 提交于 2019-12-07 18:29:38

问题


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


回答1:


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



回答2:


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.



来源:https://stackoverflow.com/questions/44730318/center-a-string-by-padding-spaces-up-to-a-specified-length

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