Home > Enterprise >  Shift alphabetical characters in string
Shift alphabetical characters in string

Time:12-29

Let's say I have a string:

s <- 'hello world zzz'

I want to shift the alphabetical characters up by one.

So:

  • a becomes b

  • b becomes c

  • c becomes d

  • d becomes e

and so on...

  • w becomes x

  • x becomes y

  • y becomes z

And:

  • z becomes a

The other condition is that if there is character that isn't in the alphabet (in this case the space), keep the characters as it is, so the space remains as a space.


Would all this be possible?

My desired output here would be:

ifmmp xpsme aaa

I have tried:

new <- c()
for (i in s) 
    {
    new <- c(new, 'abcdefghijklmnopqrstuvwxyz'[which('abcdefghijklmnopqrstuvwxyz' == i)   1])
    }

print(new)

But it doesn't work...

Any ways of doing this?

CodePudding user response:

chartr("abcdefghijklmnopqrstuvwxyz", "bcdefghijklmnopqrstuvwxyza", 'hello world zzz')
# [1] "ifmmp xpsme aaa"

(A function I've never had cause to use ...)

  • Related