How to use Inbuilt Functions In R Programs
R provides convenient inbuilt functions to reverse strings. We use rev() and strsplit() to reverse the string and then compare it with the original.
R
# Function to check if a string is a palindrome isPalindrome <- function (s) { s <- tolower (s) s <- gsub ( " " , "" , s) rev_s <- paste ( rev ( strsplit (s, NULL )[[1]]), collapse = "" ) return (s == rev_s) } # Predefined input (change this string as needed) user_input <- "13431" # 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 starts by converting the input string s to lowercase using tolower(s) to ensure a case-insensitive comparison.
- It then uses gsub(” “, “”, s) to remove spaces from the string, making it space-agnostic.
- Next, the code reverses the processed string s using rev and paste, storing the result in rev_s.
- Finally, it checks if the original string s is equal to the reversed string rev_s and returns YES if they match, indicating a palindrome, or NO otherwise.
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.