Are these two an anagram
A word game checks whether one phrase uses exactly the same letters as another.
- Case does not matter.
- Whitespace is ignored entirely.
- Everything else — digits, punctuation — counts as a character that has to match.
- Two empty phrases are an anagram of each other.
isAnagram(text: string, other: string) → bool
C++ needs a compiler and Drill does not host one yet, so this page is the reference rather than an exercise: the problem, worked examples, and the solution in full. To type it out, the same problem runs in Python.
Where you start
bool isAnagram(std::string text, std::string other) {
}
Worked examples
| Call | Result |
|---|---|
isAnagram(std::string("Listen"), std::string("Silent")) | true |
isAnagram(std::string("a b"), std::string("ba")) | true |
isAnagram(std::string("hello"), std::string("world")) | false |
isAnagram(std::string("abc"), std::string("ab")) | false |
Hint
Strip and lowercase both, then compare the sorted characters, or count them.
Reference solution in C++
bool isAnagram(std::string text, std::string other) {
auto clean = [](const string& s) {
string r;
for (char c : s) {
if (isspace(static_cast<unsigned char>(c))) continue;
r += static_cast<char>(tolower(static_cast<unsigned char>(c)));
}
std::sort(r.begin(), r.end());
return r;
};
return clean(text) == clean(other);
}