If you have any query feel free to chat us!
Happy Coding! Happy Learning!
To check if two strings are anagrams, it means that the two strings have the same characters but in a different order, and each character appears the same number of times in both strings. Here's a C++ program to determine if two strings are anagrams:
cppCopy code
#include <iostream> #include <string> #include <algorithm> bool areAnagrams(const std::string& str1, const std::string& str2) { if (str1.length() != str2.length()) { return false; // Anagrams must have the same length } // Sort the characters in both strings std::string sortedStr1 = str1; std::string sortedStr2 = str2; std::sort(sortedStr1.begin(), sortedStr1.end()); std::sort(sortedStr2.begin(), sortedStr2.end()); // Compare the sorted strings to check for anagrams return sortedStr1 == sortedStr2; } int main() { std::string str1, str2; std::cout << "Enter the first string: "; std::getline(std::cin, str1); std::cout << "Enter the second string: "; std::getline(std::cin, str2); if (areAnagrams(str1, str2)) { std::cout << "The two strings are anagrams." << std::endl; } else { std::cout << "The two strings are not anagrams." << std::endl; } return 0; }
In this program, the
areAnagrams
function checks if two strings are anagrams. It first ensures that the two strings have the same length (an essential condition for being anagrams). Then, it sorts the characters in both strings using thestd::sort
function from the<algorithm>
header. Finally, it compares the sorted strings. If they are equal, it means the strings are anagrams.Sample Input:
cCopy code
Enter the first string: listen Enter the second string: silent
Sample Output:
sqlCopy code
The two strings are anagrams.
The program correctly identifies that the input strings "listen" and "silent" are anagrams of each other.
Note: The program assumes that the input strings are case-sensitive. If you want to perform a case-insensitive comparison, you can convert both strings to lowercase or uppercase before calling the
areAnagrams
function.
Start the conversation!
Be the first to share your thoughts
Quick answers to common questions about our courses, quizzes, and learning platform