OneBite.Dev - Coding blog in a bite size

reverse a string in R

Code snippet on how to reverse a string in R

revString <- function(string){
  revStr <- string
  length <- nchar(revStr)
  for(i in 1:length){
    revStr <- substr(revStr,length-i+1,length-i+1) 
              + substr(revStr,1,length-i)
  }
  return(revStr)
}

This code creates a small function that can be used to reverse a string in R. The function is called “revString” and requires one input, the string that needs to be reversed.

It first creates a placeholder variable that stores the string, then it creates a variable that stores the length of the string.

A for loop is then used to iterate over the string from the last character to the first one. At each iteration, the new reversed string is created by taking the last iteration’s character and adding it to the result of the substring of the original string from position 1 to the next to last character.

This loop continues until all characters have been added to the reversed result and the function finally returns the reversed string.

r