Program to Check if Two Strings Are Anagrams or Not
2025-11-04
anagram program
python
c
js
php
csharp
interview programs
Learn how to check whether two strings are anagrams using simple logic and sorting techniques. This program compares characters of both strings and identifies if they contain the same letters in the same frequency. Includes explanation and code in Python, C, C#, JavaScript, and PHP.
Program Explanation
What are Anagrams?
Two strings are called anagrams if they contain the same characters in the same quantity, but possibly in a different order. Example: "listen" and "silent" are anagrams.
Steps to Check if Two Strings Are Anagrams
- Take two strings as input.
- Convert both strings to the same case (optional but recommended).
- Remove spaces if needed (based on requirement).
- Sort both strings alphabetically.
- If sorted results are equal → the strings are anagrams.
- Otherwise → they are not anagrams.
Key Points
- Anagram checking usually ignores case (e.g., "Army" and "Mary").
- Spaces can be removed for multi-word strings ("Debit Card" ↔ "Bad Credit").
- Sorting is the simplest method, but frequency counting is also used.
Program Code
s1 = input("Enter first string: ")
s2 = input("Enter second string: ")
if sorted(s1.lower()) == sorted(s2.lower()):
print("Strings are Anagrams")
else:
print("Strings are Not Anagrams")
#include <stdio.h>
#include <string.h>
#include <ctype.h>
void sortString(char *str) {
int len = strlen(str);
for (int i = 0; i < len - 1; i++) {
for (int j = i + 1; j < len; j++) {
if (str[i] > str[j]) {
char temp = str[i];
str[i] = str[j];
str[j] = temp;
}
}
}
}
int main() {
char s1[100], s2[100];
printf("Enter first string: ");
scanf("%s", s1);
printf("Enter second string: ");
scanf("%s", s2);
sortString(s1);
sortString(s2);
if (strcmp(s1, s2) == 0)
printf("Strings are Anagrams");
else
printf("Strings are Not Anagrams");
return 0;
}
let s1 = prompt("Enter first string:");
let s2 = prompt("Enter second string:");
let sort1 = s1.toLowerCase().split("").sort().join("");
let sort2 = s2.toLowerCase().split("").sort().join("");
if (sort1 === sort2)
console.log("Strings are Anagrams");
else
console.log("Strings are Not Anagrams");
using System;
using System.Linq;
class Program {
static void Main() {
Console.Write("Enter first string: ");
string s1 = Console.ReadLine();
Console.Write("Enter second string: ");
string s2 = Console.ReadLine();
string sort1 = new string(s1.ToLower().OrderBy(c => c).ToArray());
string sort2 = new string(s2.ToLower().OrderBy(c => c).ToArray());
if (sort1 == sort2)
Console.WriteLine("Strings are Anagrams");
else
Console.WriteLine("Strings are Not Anagrams");
}
}
<?php
$s1 = readline("Enter first string: ");
$s2 = readline("Enter second string: ");
$sort1 = str_split(strtolower($s1));
$sort2 = str_split(strtolower($s2));
sort($sort1);
sort($sort2);
if ($sort1 == $sort2)
echo "Strings are Anagrams";
else
echo "Strings are Not Anagrams";
?>
