如何在R中用一盒X包围一个字符串?

时间:2017-03-05 01:28:55

标签: r string stringr

这是任务:

编写一个打印出盒装句子的函数,如下所示:

s<-"This is a sentence with different word lengths"

框打印以下“

XXXXXXXXXXXXX
X   this    X
X    is     X
X     a     X
X sentence  X
X   with    X
X different X
X   word    X
X  lengths  X
XXXXXXXXXXXXX

诀窍是每个单词都应该在X的框内居中 因此,X的顶部和底部字符串的长度应为4 加上最长单词的长度右边的所有X都应排成一行。应该没有引号。

首先,我写了这一行:

s<-cat("This","is","a","sentence","with","different","word","lengths",sep=" ",fill=2)

包装文本,以便每行有一个单词。我不知道如何让X在包裹的字符串周围形成一个盒子。我想我应该使用nchar(s),但我不确定它是如何有用的。任何帮助,将不胜感激!

1 个答案:

答案 0 :(得分:3)

您可以先在句子中计算最大单词的长度,然后“X” max_word_length + 4
这些空间应该分成两个方面。

s<-"This is a sentence with different word lengths"
library(stringr)
surround_x <- function(string){
  word_vec <- str_split(string, pattern = " ")[[1]]
  max_length <- max(nchar(word_vec))
  cat(str_c(rep("X", max_length + 4), collapse = ""),"\n")
  for(i in word_vec){
    space_num <- max_length + 2 - nchar(i)
    start_space_num <- floor(space_num/2)
    end_space_num <- space_num - start_space_num
    string <- str_c(c("X", rep(" ", start_space_num), i ,rep(" ", end_space_num), "X"), collapse = "")
    cat(string, "\n")
  }
  cat(str_c(rep("X", max_length + 4), collapse = ""),"\n")
}

结果是:

> surround_x(s)
XXXXXXXXXXXXX 
X   This    X 
X    is     X 
X     a     X 
X sentence  X 
X   with    X 
X different X 
X   word    X 
X  lengths  X 
XXXXXXXXXXXXX