C Program to check anagram by sorting strings
Program
#include<stdio.h>
#include<string.h>
int check_anagram(char strOne[], char strTwo[])
{
int i, j, n;
char temp;
int strOneLen = strlen(strOne);
int strTwoLen = strlen(strTwo);
if(strOneLen != strTwoLen)
return 0;
n = strOneLen;
for(i = 0; i < n - 1; i++)
{
for(j = i + 1; j < n; j++)
{
if(strOne[i] > strOne[j])
{
temp = strOne[i];
strOne[i] = strOne[j];
strOne[j] = temp;
}
if(strTwo[i] > strTwo[j])
{
temp = strTwo[i];
strTwo[i] = strTwo[j];
strTwo[j] = temp;
}
}
}
for(i = 0; i < n; i++)
{
if(strOne[i] != strTwo[i])
return 0;
}
return 1;
}
void main()
{
char strOne[100], strTwo[100];
printf("Enter string 1:\t");
scanf("%s", strOne);
printf("Enter string 2:\t");
scanf("%s", strTwo);
if(check_anagram(strOne, strTwo) == 1)
{
printf("The strings are anagrams\n");
}
else
{
printf("The strings are not anagrams\n");
}
}
Output 1
$ gcc anagram-by-sorting-strings.c
$ ./a.out
Enter string 1: articles
Enter string 2: recitals
The strings are anagrams
Output 2
$ gcc anagram-by-sorting-strings.c
$ ./a.out
Enter string 1: hello
Enter string 2: world
The strings are not anagrams