String Anagram Code in Java
String Anagram Code | Java
A string anagram is a word or phrase formed by rearranging the letters of another word or phrase, typically using all the original letters exactly once. For example, "listen" and "silent" are anagrams of each other.
import java.util.*;
class HelloWorld {
public static void main(String[] args) {
String s1 = "asgar";
String s2 = "agsag";
if(s1.length() != s2.length()){
System.out.println("not Anagram");
}
char a[]= s1.toCharArray();
char b[] = s2.toCharArray();
Arrays.sort(a);
Arrays.sort(b);
boolean ismatch = Arrays.equals(a,b);
if(ismatch){
System.out.println(" Anagram");
}else{
System.out.println("not Anagram");
}}};
output:
not Anagram
public static void main(String[] args) {
ReplyDeleteString f1 = "aasasa";
String s1 = "aasasa";
if(f1.length() != s1.length()){
System.out.println("not anagram------>");
return;
}
char []f1Arr = f1.toCharArray();
char[] s1Arr = s1.toCharArray();
Arrays.sort(f1Arr);
Arrays.sort(s1Arr);
boolean result = Arrays.equals(f1Arr,s1Arr);
if(result){
System.out.println(" anagram------>");
}else{
System.out.println("not anagram------>");
}
}
}