2021年4月8日星期四

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?

https://stackoverflow.com/questions/67013326/replace-order-or-character-in-a-string April 09, 2021 at 07:57AM

没有评论:

发表评论