Ad space (banner)
๐Ÿ“ŠR Lessons
Lesson 43 / 68

Reversing a string and testing for a palindrome

This lesson covers reversing a string and testing for a palindrome in R, with the aim of understanding the basics of string handling.

rev() reverses a vector of characters. A string that reads the same forwards and backwards is a palindrome.

In the sample code, is_palindrome() splits the string into single characters with strsplit(s, "")[[1]], reverses it with rev(), rebuilds it with paste(..., collapse = ""), and compares with the original. "racecar" reads the same reversed, so it is judged a palindrome.

A common early stumble is that R has no function to reverse a string directly — you have to split into a character vector first and then use rev(). The extra step is confusing at first.

Reversal and palindrome checks rarely come up directly in practice, but they make good practice at converting between strings and vectors.

๐Ÿ“– Reference code
โœ๏ธ Your code
Type your code, then press "Run"

๐Ÿงช This site can't compile or run R directly, so it checks on the spot whether what you typed matches the reference code (scoring happens entirely in your browser โ€” nothing is sent anywhere).

Ad space (banner)
Ad space (in-article)