1

This is the task:

write a function that prints out a boxed sentence as follows:

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

box(s) prints the following"

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

The trick is that every word should be centered inside the box of X's The length of the top and bottom string of X's should therefore be 4 plus length of longest word All X's on the right should line up. There should be no quotes.

To start, I wrote this line:

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

which wraps the text so that there is one word on each line. I am not sure how to get the X's to form a box around the wrapped string. I think I am supposed to use nchar(s), but I am not sure how it is useful. Any help would be appreciated!

Psidom
  • 209,562
  • 33
  • 339
  • 356
  • This seems really incomplete and somewhat confused. The cat function returns NULL so it makes no sense to execute that second assignment. – IRTFM Mar 05 '17 at 01:45
  • I am not sure how else to wrap the string so that there is one word on each line. I am very new to R and just started taking this class. Do you have any other recommendations? @42 – maddiemoore2729 Mar 05 '17 at 01:48
  • `cat( paste( strsplit( s, " ")[[1]], "\n") )`. And be sure to give appropriate credit to Vida Wang when you turn in your homework assignment. – IRTFM Mar 05 '17 at 02:20

1 Answers1

3

You can first calculate the max word's length in the sentence, then the "X" will be max_word_length + 4
And the spaces should be split into two side.

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")
}

The result is :

> 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
Vida Wang
  • 406
  • 2
  • 7