School-Coding-Cpp/sfusi/isAnagram.cpp

70 lines
1.2 KiB
C++

/*
Nome: Mario
Cognome: Montanari
isAnagram
*/
#include <iostream>
#include <cstring>
#include <cctype>
#define SIZE 100+1
#define NUM_LETT 26
using namespace std;
bool isAnagram(char *src1, char *src2);
int main(void) {
char src1[SIZE];
char src2[SIZE];
cout << "Prima parola: ";
cin.getline(src1, SIZE);
cout << "Seconda parola: ";
cin.getline(src2, SIZE);
if (isAnagram(src1, src2)) {
cout << "Le due parole sono anagrammi." << endl;
} else {
cout << "Le due parole non sono anagrammi." << endl;
}
return 0;
}
bool isAnagram(char *src1, char *src2) {
for (int i = 0; i < strlen(src1); i++) {
src1[i] = tolower(src1[i]);
}
for (int i = 0; i < strlen(src2); i++) {
src2[i] = tolower(src2[i]);
}
if (strlen(src1) != strlen(src2)) {
return false;
}
for (int i = 0; i < strlen(src1); i++) {
if (strchr(src2, src1[i]) == NULL) {
return false;
}
}
int count[26] = {0};
for (int i = 0; i < strlen(src1); i++) {
count[tolower(src1[i]) - 'a']++;
count[tolower(src2[i]) - 'a']--;
}
for (int i = 0; i < NUM_LETT; i++) {
if (count[i] != 0) {
return false;
}
}
return true;
}