Open In App

How to reverse a string in R

Reversing a string means changing its order so that the last character becomes the first, the second last character becomes the second, and so on. A while loop is a control flow statement used in R programming to execute a block of code repeatedly as long as a specified condition is true. By using a while loop, we can easily reverse a given string in various programming languages.

Example:

input string : geeks



reversed string : skeeg

Concepts related to the topic:

  1. Strings: A sequence of characters in programming, which can be manipulated and processed.
  2. While Loop: A control structure that repeatedly executes a block of code as long as a given condition is true.
  3. Indexing: The ability to access individual characters in a string using their position or index.

Steps needed:

  1. Initialize two variables, one for the original string and one for the reversed string.
  2. Start a while loop with the condition that the length of the original string is greater than 0.
  3. Inside the loop, extract the last character of the original string and append it to the reversed string.
  4. Remove the last character from the original string.
  5. Repeat steps 3 and 4 until all characters are processed.
  6. Print or return the reversed string.

Example 1 : Reverse a string using a while loop




reverseStr <- function(str) {
  reversedStr <- ""
  while (nchar(str) > 0) {
    reversedStr <- paste0(reversedStr, substr(str, nchar(str), nchar(str)))
    str <- substr(str, 1, nchar(str) - 1)
  }
  return(reversedStr)
}
 
# Example usage
str <- "Hello, R!"
reversedStr <- reverseStr(str)
print(reversedStr)

Output:



[1] "!R ,olleH"

Example 2: Reverse a string using a repeat loop




reverseStr <- function(str) {
  reversedStr <- ""
  repeat {
    if (nchar(str) == 0) break
    reversedStr <- paste0(reversedStr, substr(str, nchar(str), nchar(str)))
    str <- substr(str, 1, nchar(str) - 1)
  }
  return(reversedStr)
}
 
# Example usage
str <- "R is awesome!"
reversedStr <- reverseStr(str)
print(reversedStr)

Output:

[1] "!emosewa si R"

Example 3: Reverse a string using a while loop with pointers




reverseStr <- function(str) {
  reversedStr <- ""
  ptr <- nchar(str)
  while (ptr > 0) {
    reversedStr <- paste0(reversedStr, substr(str, ptr, ptr))
    ptr <- ptr - 1
  }
  return(reversedStr)
}
 
# Example usage
str <- "Loop in R!"
reversedStr <- reverseStr(str)
print(reversedStr)

Output:

[1] "!R ni pooL"

Article Tags :