Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

replace order or character in a string

Tags:

r

I'm trying to learn r and I came accross an exerscie that I dont know how to solve. I'm trying to write a function that takes a string as argument and flips the characters of each word.

For example:

sentence.flipper("the quick brown fox jumped over the lazy dog")

should return "eht kciuq nworb xof depmuj revo eht yzal god"

So far I have written this

sentence.flipper = function(str) {

  str.words = strsplit(str, split=" ")  
  rev.words = lapply(str.words, word.flipper)  
  str.flipped = paste(rev.words, sep=" ")
  return(str.flipped)
}

word.flipper = function(str) {
 #browser()
  chars = strsplit(str, split=" ")
  chars.flipped = rev(chars)
  str.flipped = paste(chars.flipped , collapse=" ")
  return(str.flipped)

but this returns "dog lazy the over jumped fox brown quick the"

how can I fix this to get the desired output?

like image 861
Daniel Avatar asked Jun 10 '26 01:06

Daniel


1 Answers

First split the sentence in words, then split each word into character, reverse them and paste them together.

sentence.flipper = function(str) {
paste0(sapply(strsplit(strsplit(str, '\\s+')[[1]], ''), 
        function(x) paste0(rev(x), collapse = '')), collapse = ' ')
}

sent <- "the quick brown fox jumped over the lazy dog"

sentence.flipper(sent)
#[1] "eht kciuq nworb xof depmuj revo eht yzal god"
like image 133
Ronak Shah Avatar answered Jun 16 '26 19:06

Ronak Shah