通过填充空格到指定长度来居中字符串 [英] center a string by padding spaces up to a specified length
问题描述
我有一个名字矢量,像这样:
I have a vector of names, like this:
x <- c("Marco", "John", "Jonathan")
我需要对其进行格式化,以便通过添加前导和尾随空格来使名称集中在10个字符的字符串中:
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 "
我希望解决方案比使用paste
,rep
和计算nchar
复杂吗? (也许使用sprintf
,但我不知道如何操作.)
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).
推荐答案
这是一个sprintf()
解决方案,它使用简单的辅助矢量f
确定低边宽度.然后,我们可以使用*
字符将宽度插入到我们的格式中,并使用右侧的ceiling()
来计算名称中的奇数个字符.由于我们的最大字符宽度为10,因此每个超过10个字符的名称都将保持不变,因为我们使用pmax()
调整了这些宽度.
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"
数据:
x <- c("Marco", "John", "Jonathan", "Christopher")
这篇关于通过填充空格到指定长度来居中字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!