Grupo
Estructuras Condicionales Avanzadas en C++
Ojetivo
1. Solicitar al usuario que introduzca dos cadenas.
2. Convertir ambas cadenas a minúsculas para garantizar una comparación sin distinción entre mayúsculas y minúsculas.
3. Ordenar los caracteres de ambas cadenas alfabéticamente.
4. Comparar las cadenas ordenadas.
5. Mostrar si las dos cadenas son anagramas.
Crear un programa que determine si un par de cadenas son anagramas.
Ejemplo de Código C++
Mostrar Código C++
#include <iostream> // Include input/output stream library
#include <algorithm> // Include algorithm library for sort and transform
#include <string> // Include string library
using namespace std;
bool areAnagrams(string str1, string str2) {
// Convert both strings to lowercase
transform(str1.begin(), str1.end(), str1.begin(), ::tolower);
transform(str2.begin(), str2.end(), str2.begin(), ::tolower);
// Sort both strings
sort(str1.begin(), str1.end());
sort(str2.begin(), str2.end());
// Compare sorted strings
return str1 == str2;
}
int main() {
string word1, word2; // Variables to store user input
// Prompt the user for the first word
cout << "Enter the first word: ";
cin >> word1;
// Prompt the user for the second word
cout << "Enter the second word: ";
cin >> word2;
// Check if the words are anagrams
if (areAnagrams(word1, word2)) {
cout << "The words are anagrams." << endl;
} else {
cout << "The words are not anagrams." << endl;
}
return 0; // End of program
}
Salida
Enter the first word: listen
Enter the second word: silent
The words are anagrams.
Comparte este ejercicio C++