R Program to Reverse a String

1. Introduction

A common task in programming and data manipulation is string reversal. Whether for algorithms, puzzles, or string operations, knowing how to reverse a string is a handy skill. In this guide, we will demonstrate how to reverse a string in the R programming language.

2. Program Overview

The program will:

1. Prompt the user to input a string.

2. Reverse the string.

3. Display the reversed string.

3. Code Program

# Prompt the user for a string
cat("Enter the string to be reversed: ")
input_string <- readLines(n=1)

# Reverse the string using stringi package function
library(stringi)
reversed_string <- stri_reverse(input_string)

# Display the reversed string
cat("Reversed string:", reversed_string, "\n")

Output:

Enter the string to be reversed: Hello World
Reversed string: dlroW olleH

4. Step By Step Explanation

1. The program starts by prompting the user to enter a string using the cat function. The entered string is captured using the readLines function.

2. To reverse the string, we employ the stri_reverse function from the stringi package. If you don't have the stringi package installed, you can add it using the command install.packages("stringi").

3. The reversed string is then displayed to the user using the cat function.

Comments