如何使用sprintf函数添加前导"0"而不是字符的空格? [英] How to use sprintf function to add leading "0" instead of spaces to character?

查看:649
本文介绍了如何使用sprintf函数添加前导"0"而不是字符的空格?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用sprintf函数在字符中添加前导"0",并使所有字符具有相同的长度.但是我得到的是领先的空间.

I am trying to use sprintf function to add leading "0" to character, and make all charaters the same length. However what I get is leading space.

我的代码:

a <- c("12","123", "1234")
sprintf("%04s",a)
[1] "  12" " 123" "1234"

我试图得到的东西:

[1] "0012" "0123" "1234"

sprintf手册说:对于字符,在某些平台上此零填充而在其他平台上则被忽略."

The sprintf manual says: "For characters, this zero-pads on some platforms and is ignored on others."

我的版本: 平台x86_64-w64-mingw32
拱形x86_64
os mingw32
系统x86_64,mingw32
状态
专业3
次要1.0
2014年
第04个月
第10天
svn rev 65387
语言R
version.string R版本3.1.0(2014-04-10) 昵称春之舞

My version: platform x86_64-w64-mingw32
arch x86_64
os mingw32
system x86_64, mingw32
status
major 3
minor 1.0
year 2014
month 04
day 10
svn rev 65387
language R
version.string R version 3.1.0 (2014-04-10) nickname Spring Dance

推荐答案

如果您在仅插入空格的平台上,则regex是您的朋友.像

If you are on a platform which only inserts spaces, regex is your friend. Something like

foo<- gsub('^[ ]{1,}','0',bar)

这将用0替换所有前导空格.我知道可以告诉正则表达式用N零字符替换N空间,但是我确切地忘记了如何.

That will replace all leading spaces with a 0 . I know regex can be told to replace N spaces with N zero-chars, but I forget exactly how.

对于那些paste0反对者,怎么样:

to those paste0 naysayers, how about:

wantlength <- 12 # the desired final string size, fully zero padded
paste0( paste0(rep('0',wantlength-nchar(foo)),collapse='') ,foo)

这篇关于如何使用sprintf函数添加前导"0"而不是字符的空格?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆