Daniel
Daniel

Reputation: 5381

replace order or character in a string

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?

Upvotes: 3

Views: 84

Answers (2)

Paul
Paul

Reputation: 2959

Here's a one liner using {stringi}

library(stringi)
paste(sapply(stri_split(d, regex = "\\s"), stri_reverse), collapse = " ")

I realise this doesn't answer the OP by writing a function, but the strength of R knowing about and using the library of functions that already exist.

fun <- function(x) paste(sapply(stri_split(x, regex = "\\s"), stri_reverse), collapse = " ")

fun("the quick brown fox jumped over the lazy dog")

Upvotes: 4

Ronak Shah
Ronak Shah

Reputation: 388862

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"

Upvotes: 4

Related Questions