我有一个字符串向量,每个字符串应该有8个字母数字字符.它们可能在字符串中包含一个或多个空格within,而不是右或左.
对于那些少于8个字符的字符串,我想填充现有的空格,以便最终所有字符串都有8个字符.间距/填料应保持在within mm.(背景:这与英国邮政编码有关)
我的方法很复杂,可能有缺陷,下面是一个示例向量和期望输出.
## x can take any alphanumeric value
x <- c("xxx xxx", "xx xxx", "x xxx", "xxx xxx", "xx xxx", "xxxxxxxx")
## missing number of spaces
s_miss <- 8 - nchar(x)
## numbers of spaces
s_pres <- stringr::str_count(x, "\\s")
## now here is a convoluted function
## if a space is found, the missing spaces will be added to the already present spaces
padded <- sapply(1: length(x), function(i){
gsub("\\s+", paste(rep(" ", s_pres[i] + s_miss[i]), collapse = ""), x[i])})
## desired output
padded
#> [1] "xxx xxx" "xx xxx" "x xxx" "xxx xxx" "xx xxx" "xxxxxxxx"
nchar(padded)
#> [1] 8 8 8 8 8 8