A "palindrome" is a word (or sentence) whose letters are the same forward as backward. Words like "kayak," "rotor," and "dad" are palindromes.
There are palindromic phrases too, like "was it a car or a cat i saw." Typically, spaces and punctuation are ignored.
Let's write a program that will tell you if a word (or phrase) is a palindrome. Here's the needed logic:
Read a string and convert it to lowercase for a "safe" comparison.
Remove the spaces from the string
Compare the original string to the reverse space-free string and see if they match.
Here are the three string functions we'll use:
string.sub(string,start,end) and string.reverse(string)
Move the mouse over a dotted box for more information.
Now you try. See if you can fix the if statement to test if string b is equal to its reversed version.
Type your code here:
See your results here:
This code will not work, but here's the logic. See if you can get it working by fixing the if statement:
Read a string into variable a and convert it to lowercase.
Start a for-loop with the variable i from 1 to the length ofa.
Extract the single character at position i in string a using the string.sub function. If
it's not a space (~= " ") then concatenate the character to a new string called b.
At the conclusion of the for-loop, variable b contains a space-free version of the original string.
Now it's your turn. What condition would you put in the if statement to see if b is equal to its reverse? This
is the "palindrome test."
Here are some test words (see Wikipedia): civic, radar, level, rotor, kayak, reviver, racecar, redder, madam, toot, boob, malayalam, pop, noon, and refer.
Here are some test phrases (Wikipedia): "Was it a rat I saw" or "Never odd or even"
Show a friend, family member, or teacher what you've done!
Here is a share link to your code:
Does your code work? Want to run it on your iPhone?
Here's your code:
Use [Control]-[C] (Windows) or [⌘]-[C] (MacOS) to copy your code.
Paste it using [Control]-[V] (Windows) or [⌘]-[V] (MacOS) into
Then click the "Use on iPhone" button that you'll see.