C++ bootcamp · Lab 29

Anagram 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 two words and print yes if they are anagrams of each other, otherwise no.

Compare case-insensitively. Two words are anagrams when they use the same letters, just rearranged.

Input. Two words, whitespace-separated.

Output. yes or no.

Examples

Example 1
Input
listen silent
Output
yes
Example 2
Input
hello world
Output
no
Hint
  1. Lowercase both strings, sort their characters, then compare.
  2. std::sort(s.begin(), s.end());
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 a, b;
  std::cin >> a >> b;
  for (char& ch : a) ch = std::tolower((unsigned char)ch);
  for (char& ch : b) ch = std::tolower((unsigned char)ch);
  std::sort(a.begin(), a.end());
  std::sort(b.begin(), b.end());
  std::cout << (a == b ? "yes\n" : "no\n");
  return 0;
}
main.cppC++17 · g++ · Ctrl + Enter runs
ResultIdle
Run to see output. Check grades the tests.