C++ bootcamp · Lab 15

Palindrome check

mediumStrings12 minLesson: Strings

Read the question, write C++ on the right, then Run or Check.

QuestionHint and solution stay closed until you open them

Read one word and print yes if it reads the same forwards and backwards, otherwise no.

Ignore case: Level should count as a palindrome.

Input. One line: a word.

Output. yes or no (lowercase).

Examples

Example 1 — Case-insensitive.
Input
Level
Output
yes
Example 2
Input
python
Output
no
Hint
  1. Lowercase the whole word first so case does not break the comparison.
  2. Build a reversed copy with std::string r(s.rbegin(), s.rend()); then compare s == r.
Show correct code

Peek only after you have tried. You can still Check your own version.

#include <iostream>
#include <string>
#include <algorithm>
#include <cctype>

int main() {
  std::string s;
  std::cin >> s;
  for (char& ch : s) ch = std::tolower((unsigned char)ch);
  std::string r(s.rbegin(), s.rend());
  std::cout << (s == r ? "yes\n" : "no\n");
  return 0;
}
main.cppC++17 · g++ · Ctrl + Enter runs
ResultIdle
Run to see output. Check grades the tests.