adsense

Hii, welcome to my site. My name is Om prakash kartik. This blog helps you to learn programming languages concepts.

Program in C and C++ to check whether two strings are an anagram or not

Program in C and C++ to check whether two strings are an anagram or not

C Program
#include<stdio.h>
#include<stdlib.h>
 enum bool {false, true}; // create boolean enum
 typedef enum bool bool; 
 bool isAnagrams(char *str, char *str1){
 	int fst[26] = {0}, snd[26] = {0}, i;
 	for(i = 0; str[i] != '\0' ; i++){
 		  str[i] = tolower(str[i]);
		  fst[str[i] - 'a']++;
	 }
	for(i = 0; str1[i] != '\0' ; i++){
 		  str1[i] = tolower(str1[i]);
		  snd[str1[i] - 'a']++;
	 }
	for(i = 0; i < 26 ; i++){
	 if(fst[i] != 0 || snd[i] != 0)
       if(fst[i] != snd[i]){
 		  return false;
       }  
	 }
    return true; 
 }
 int main(){
    char *str = malloc(100) , *str1 = malloc(100);
    printf("Enter 1st string :- ");
    gets(str);
    printf("Enter 2nd string :- ");
    gets(str1);
    if(isAnagrams(str,str1) == true)
        printf("Anagrams");
    else
       printf("Not Anagrams");
    return 0;
 }
C++ Program
    
    #include<iostream>
 using namespace std;
 bool isAnagrams(char *str, char *str1){
 	int fst[26] = {0}, snd[26] = {0}, i;
 	for(i = 0; str[i] != '\0' ; i++){
 		  str[i] = tolower(str[i]);
		  fst[str[i] - 'a']++;
	 }
	for(i = 0; str1[i] != '\0' ; i++){
 		  str1[i] = tolower(str1[i]);
		  snd[str1[i] - 'a']++;
	 }
	for(i = 0; i < 26 ; i++){
	 if(fst[i] != 0 || snd[i] != 0)
       if(fst[i] != snd[i]){
 		  return false;
       }  
	 }
    return true; 
 }
 int main(){
    char *str = new char[100] , *str1 = new char[100];;
    cout<<"Enter 1st string :- ";
    cin.getline(str,99);
    cout<<"Enter 2nd string :- ";
    cin.getline(str1,99);
    if(isAnagrams(str,str1) == true)
       cout<<"Anagrams";
    else
       cout<<"Not Anagrams";
    return 0;
 }
Output :-







Related Programs

Post a Comment

0 Comments