An anagram is a play on words created by rearranging the letters of the original word to make a new word or phrase.
(Listen = Silent, Tar = Rat, State = Taste, etc)
In this example, we’ll learn How to Find if Two Strings are Anagrams.
The program takes two strings and checks if they are anagrams.
C+ Code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 |
#include <iostream> using namespace std; int anagram(char str1[], char str2[]) { int i, flag = 0, x[26] = {0}, y[26] = {0}; for(i = 0; str1[i] != '\0'; i++) x[str1[i] - 'a']++; for(i = 0; str2[i] != '\0'; i++) y[str2[i] - 'a']++; for (i = 0; i < 26; i++) { if (x[i] != y[i]) flag = 1; } if (flag == 1) cout << "Entered strings are not anagrams."; else cout << "Entered strings are anagrams."; } int main () { char str1[50], str2[50]; int flag; cout << "Enter string 1 : "; gets(str1); cout << "Enter string 2 : "; gets(str2); anagram(str1, str2); return 0; } |
Output: