如何用 R 中的 X 框包围字符串?

How to surround a string with a box of X's in R?

这是任务:

写一个函数,打印出一个带框的句子如下:

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

box(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

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

首先,我写了这一行:

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

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

你可以先计算出句子中的最大字长,那么"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