Exercise: Palindromes
Now that you know how to read a line from stdin:
char s[100];
fgets(s, 100, stdin);
let me give you an exercise. Assuming that the line you read contains both letters and non-letters, such as spaces, punctuation, and possibly the '\n' character at end end, check if the given line is a palindrome. A palindrome is a word or a sentence which reads the same from left to right and from right to left, if we ignore whitespace and punctuation:
Was it a car or a cat I saw?
To check if it's a palindrome or not, you will need to know a few things.
First, since we only expect to see English sentences, we can check that a given character c is a letter by using isalpha(c) (you need to #include <ctype.h>). For regular English letters you could as well do
if ((c >= 'A' && c <= 'Z') || (c >= 'a' || c <= 'z')) {
...
}
but if (isalpha(c)) will do it for you, and will also work for system locales other than English.
Next, we want our palindrome to allow both uppercase and lowercase character. You can use tolower(c) to convert a character to lowercase, or toupper(c) to convert it to uppercase. Just choose one.
Finally, you need to figure out how to skip non-letters. One useful approach for this kind of tasks is to have to variables, l and r, pointing to characters from the left and from the right end of the string. Increment l while s[l] is not a letter, then decrement r while s[r] is not a letter; then compare s[l] and s[r]. Do this while l < r.
Sounds easy enough? Let's do it! Print a single word, "yes\n" or "no\n", depending on if your input string is a palindrome.
#include <ctype.h>
#include <stdio.h>
#include <string.h>
int main() {
/* TODO: your code here */
}
After you finish this exercise, we'll continue talking about reading strings from stdin!