How to use an Extra Variable In R Programs
This method involves storing characters in an empty variable and comparing it with the original string. We reverse the string by building it character by character in reverse order and then compare it to the original.
R
# Function to check if a string is a palindrome isPalindrome <- function (s) { s <- tolower (s) s <- gsub ( " " , "" , s) w <- "" for (i in s) { w <- paste (i, w, sep = "" ) } return (s == w) } # Predefined input (change this string as needed) user_input <- "madam" # Check if the user input is a palindrome and print YES or NO if ( isPalindrome (user_input)) { cat ( "YES\n" ) } else { cat ( "NO\n" ) } |
Output:
YES
- The isPalindrome function:
- Converts the input string s to lowercase using tolower to make the comparison case-insensitive.
- Removes spaces from the string using gsub.
- Initializes an empty string w.
- Iterates through each character in the modified string, reversing the characters and storing them in w.
- The code then compares the original modified string s with the reversed string w to determine if they are equal.
- If they are equal we get our output as YES.
R Program to Check if a String is a Palindrome
In this article, we explore a simple yet essential task in programming: checking whether a given string is a palindrome. A palindrome is a sequence of characters that reads the same forwards and backwards, making it a common problem in text processing and string manipulation. We’ll delve into the logic and implementation of a program in the R programming language to efficiently determine if a string exhibits this intriguing property, offering practical insights for both beginners and experienced programmers.