Trusted answers to developer questions

How to know if two given strings are anagrams in C

Get Started With Data Science

Learn the fundamentals of Data Science with this free course. Future-proof your career by adding Data Science skills to your toolkit — or prepare to land a job in AI, Machine Learning, or Data Analysis.

What is an anagram?

An anagram is a word made by rearranging an original word’s letters to make a new word.

For example, “listen” and “silent” are anagrams of each other because we can create them by rearranging the other’s letters. In other words, the strings contain the same letters, but in a different order.

3.“Silent” and “Listen”

1 of 3

Code

We are using the sorting method in the C program below to figure out if two strings are anagrams:

#include <stdio.h>
#include <string.h>
void main ()
{
char s1[] = "listen";
char s2[] = "silent";
char t;
int i, j;
int n = strlen(s1);
int n1 = strlen(s2);
// If both strings are of different length, then we can directly say they are not anagrams
if( n != n1)
{
printf("%s and %s are not anagrams! \n", s1, s2);
}
// Soring both strings −
for (i = 0; i < n-1; i++)
{
for (j = i+1; j < n; j++)
{
if (s1[i] > s1[j])
{
t = s1[i];
s1[i] = s1[j];
s1[j] = t;
}
if (s2[i] > s2[j])
{
t = s2[i];
s2[i] = s2[j];
s2[j] = t;
}
}
}
// Compare both strings character by character
for(i = 0; i<n; i++)
{
if(s1[i] != s2[i])
{
printf("Given strings are not anagrams\n");
}
}
printf("Given strings are anagrams!\n");
}

RELATED TAGS

c
Did you find this helpful?