Iterative Method
This method involves comparing characters from the start and end of the string, working towards the center. If all characters match, the string is a palindrome. Here’s the code:
R
# Function to check if a string is a palindrome isPalindrome <- function (s) { s <- tolower (s) s <- gsub ( " " , "" , s) n <- nchar (s) for (i in 1:(n %/% 2)) { if ( substr (s, i, i) != substr (s, n - i + 1, n - i + 1)) { return ( FALSE ) } } return ( TRUE ) } # Predefined input (change this string as needed) user_input <- "nitin" # 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
- Function isPalindrome:
- The function takes a string s as input.
- It converts the input string to lowercase using tolower to ensure case insensitivity.
- It removes spaces from the string using gsub.
- It calculates the length of the processed string and stores it in n
- The function then begins an iterative loop with n/2 repetitions. Due to the symmetry of the comparison (from both ends towards the centre), this loop only needs to verify the first half of the string.
- If the loop completes without finding any non-matching characters, the function returns YES, indicating that the string is a palindrome.
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.