-1

I have a sentence, ['this', 'is, 'my', house']. After splitting it by using "-"as a as separator,and reversing it to[ house, my, is, this], how do I access the last part of string? and join my and is together with house to form another sentence?

rjrj
  • 3
  • 4
  • When you say " reverse of the last string" do you mean you want "esuoh"? – G5W Mar 20 '17 at 23:55
  • @G5W, Yes, I need reverse of house and 'esuoh' should be the first word of the new sentence – rjrj Mar 21 '17 at 00:04

2 Answers2

1
out <- strsplit(sentence, "-")
last <- out[length(out)]
flip <- rev(last)
word <- paste(flip, collapse='')
DBD
  • 86
  • 3
1
sentence <- c("this","is","my","house")
strsplit(sentence[4], split="")[[1]][nchar(sentence[4]):1]

This code might be a bit dense for a beginner to interpret. The [[1]] is necessary because the value of strsplit is always a list, even when it's just one vector of individual characters; the indexing extracts that vector. The indexing after that, [nchar(sentence[4]):1], reorders the letters in that vector backwards, from the last to the first, in this case c(5,4,3,2,1). The split="" argument causes the strsplit function to split the string at every possible point, i.e. between each character.

DHW
  • 1,157
  • 1
  • 9
  • 24