Check if two strings are anagrams in Java
Written by
Two words are said to be Anagrams if both of them consist of the same characters. For example: LISTEN and SILENT are anagrams. Similarly TRIANGLE and INTEGRAL are anagrams.
Note: Anagrams have same length as well.
The basic logic for anagrams are the sum of each character’s ASCII sum will be equal.
For example: SAD and DAS — ASCII of S=83, A=65 and D=68. So sum of ASCII values will be equal.
Code:
/* Program to enter two strings and check if they are anagrams*/
import java.util.*;
class Anagrams
{
public static void main()
{
Scanner inp=new Scanner(System.in);
System.out.print("\n Enter First String: ");
String s1=inp.nextLine();
System.out.print("\n Enter Second String: ");
String s2=inp.nextLine();
int n1=0,n2=0,i;
for(i=0;i<s1.length();i++)
n1=n1+s1.charAt(i);
for(i=0;i<s2.length();i++)
n2=n2+s2.charAt(i);
if(n1==n2)
System.out.println(s1+" and "+s2+" are anagrams.");
else
System.out.println(s1+" and "+s2+" are not anagrams.");
}
}
Output:
Enter First String: LISTEN
Enter Second String: SILENT
LISTEN and SILENT are anagrams.
Enter First String: rockets
Enter Second String: restock
rockets and restock are anagrams.
Enter First String: bus
Enter Second String: zub
bus and zub are not anagrams.