Introduction
A palindrome is a word, phrase, number, or other sequence of characters that reads the same forward and backward (ignoring spaces, punctuation, and capitalization). This guide will walk you through writing an R program that checks whether a given string is a palindrome.
Problem Statement
Create an R program that:
- Prompts the user to enter a string.
- Checks if the string is a palindrome.
- Displays a message indicating whether the string is a palindrome or not.
Example:
- Input:
"madam"
- Output:
"madam is a palindrome"
Solution Steps
- Read the Input String: Use the
readline()
function to take the string input from the user. - Normalize the String: Convert the string to lowercase and remove any non-alphanumeric characters to ensure that the comparison is case-insensitive and ignores spaces or punctuation.
- Check if the String is a Palindrome: Reverse the string and compare it to the original normalized string.
- Display the Result: Use the
print()
function to display whether the string is a palindrome or not.
R Program
# R Program to Check if a String is a Palindrome
# Author: https://www.javaguides.net/
# Step 1: Read the input string from the user
input_string <- readline(prompt = "Enter a string: ")
# Step 2: Normalize the string
# Convert to lowercase and remove non-alphanumeric characters
normalized_string <- tolower(gsub("[^a-zA-Z0-9]", "", input_string))
# Step 3: Check if the string is a palindrome
is_palindrome <- function(str) {
return(str == rev(strsplit(str, NULL)[[1]]) %>% paste(collapse = ""))
}
if (is_palindrome(normalized_string)) {
print(paste("\"", input_string, "\" is a palindrome", sep = ""))
} else {
print(paste("\"", input_string, "\" is not a palindrome", sep = ""))
}
Explanation
Step 1: Read the Input String
- The
readline()
function prompts the user to enter a string. The input is read as a character string.
Step 2: Normalize the String
- The
tolower()
function converts the string to lowercase to ensure case-insensitive comparison. - The
gsub()
function removes all non-alphanumeric characters (such as spaces and punctuation) from the string.
Step 3: Check if the String is a Palindrome
- The
is_palindrome()
function checks if the normalized string is equal to its reverse. The string is split into individual characters, reversed usingrev()
, and then reassembled usingpaste()
.
Step 4: Display the Result
- The program checks the result from the
is_palindrome()
function and prints whether the input string is a palindrome or not.
Output Example
Example:
Enter a string: madam
[1] "madam is a palindrome"
Example:
Enter a string: hello
[1] "hello is not a palindrome"
Conclusion
This R program demonstrates how to check if a string is a palindrome by normalizing the string and comparing it to its reverse. It covers important concepts such as string manipulation, functions, and conditional statements, making it a practical example for beginners learning R programming.