Programming Examples
Java program to check word or phrase is anagram or not
An anagram is a word or phrase made by transposing the letters of another word or phrase; for example "parliament" is an anagram of "partial men" and "software" is an anagram of "swear oft".
Write a program that figures out whether one string is an anagram of another string. The program should ignore white space and punctuation.
import java.util.*;
class Anagram
{
public static void main(String arr[])
{
Scanner sc=new Scanner(System.in);
System.out.println("Enter String 1");
String str1=sc.nextLine();
System.out.println("Enter String 2");
String str2=sc.nextLine();
boolean flag=true;
for(int a=0;a {
if(str2.indexOf(str1.charAt(a))==-1 && str1.charAt(a)!=' ')
{
flag=false;
break;
}
}
if(flag==true)
{
System.out.println("String "+str1+" is anagram of "+str2);
}
else
{
System.out.println("String "+str1+" is not a anagram of "+str2);
}
}
}
Output
Enter String 1
race
Enter String 2
care
String race is anagram of care
************************************
Enter String 1
software
Enter String 2
swear oft
String software is anagram of swear oft