Write A Program in java to accept two words and check whether they are Anagrams or not.
I need answer only from @INFINEX
Answers
Answer:
public class Main
{
static boolean anagram(String s , String s1){
int n = s.length();
int n1 = s1.length();
if(n != n1){
return false;
}
char[] c = new char[n];
char[] c1 = new char[n1];
for(int i = 0; i < n; i++){
c[i] = s.charAt(i);
}
for(int i = 0; i < n1; i++){
c1[i] = s1.charAt(i);
}
java.util.Arrays.sort(c);
java.util.Arrays.sort(c1);
if(java.util.Arrays.equals(c , c1)){
return true;
}
return false;
}
public static void main(String[] args) {
System.out.println(anagram("angel" , "glean"));
}
}
Explanation:
Answer:
■. Anagram are said to be pair of words.
■. If a word is made with the combination of letters present in the original word.
■. For example: FLOW and WOLF, LOW and OWL.
Explanation:
import java.util.*;
public class Anagram
{
public static void main ()
{
int p1, p2, i, j, t = 0;
String str1, str2;
char chr1, chr2;
Scanner in = new Scanner (System.in);
System.out.println ("Enter first word");
str1 = in.nextLine();
str1 = str1.toLowerCase();
System.out.println ("Enter second word");
str2 = in.nextLine();
str2 = str2.toLowerCase();
p1 = str1.lengtg();
p2 = str2.length();
if ( p1 == p2 )
{
for ( i = 0; i < p1; i++ )
{
chr1 = str1.charAt(i);
t = 0;
for ( j = 0; j < p2; j++ )
{
chr2 = str2.charAt(j);
if ( chr1 == chr2 )
t = 1;
}
if ( t == 0 )
break;
}
if ( t == 0 )
System.out.println ( str1 + "and" + str2 + "are not Anagram words" );
else
System.out.println ( str1 + "and" + str2 + "are Anagram words" );
}
else
System.out.println ( "Wrong Input !! Re-enter words for Anagram" );
}
}
In Output.
Type in str1 - WOLF
Type in str2 - FLOW
enter
FLOW and WOLF are Anagram words
(or)
Type in str1 - LOW
Type in str2 - WOLF
enter
LOW and WOLF are not Anagram words
NOTE:-
@samarthkrv compiled the anagram program by using array methods.
@VidyaBhandar compiled the anagram program by using if-else iteration.