anagram code in java code example
Example 1: how to find two strings are anagrams in java
import java.util.Arrays;
public class AnagramString {
static void isAnagram(String str1, String str2) {
String s1 = str1.replaceAll("\\s", "");
String s2 = str2.replaceAll("\\s", "");
boolean status = true;
if (s1.length() != s2.length()) {
status = false;
} else {
char[] ArrayS1 = s1.toLowerCase().toCharArray();
char[] ArrayS2 = s2.toLowerCase().toCharArray();
Arrays.sort(ArrayS1);
Arrays.sort(ArrayS2);
status = Arrays.equals(ArrayS1, ArrayS2);
}
if (status) {
System.out.println(s1 + " and " + s2 + " are anagrams");
} else {
System.out.println(s1 + " and " + s2 + " are not anagrams");
}
}
public static void main(String[] args) {
isAnagram("Keep", "Peek");
isAnagram("Mother In Law", "Hitler Woman");
}
}
Example 2: anagram java program
import java.util.Arrays;
public class Anagram
{
public static void main(String[] args)
{
String strOne = "silent";
String strTwo = "listen";
if(strOne.length() == strTwo.length())
{
char[] charOne = strOne.toCharArray();
char[] charTwo = strTwo.toCharArray();
Arrays.sort(charOne);
Arrays.sort(charTwo);
boolean output = Arrays.equals(charOne, charTwo);
if(output)
{
System.out.println(strOne + " and " + strTwo + " are anagram.");
}
else
{
System.out.println(strOne + " and " + strTwo + " are not anagram.");
}
}
else
{
System.out.println(strOne + " and " + strTwo + " are not anagram.");
}
}
}
Example 3: check if anagram
function isAnagram(stringA, stringB) {
stringA = stringA.toLowerCase().replace(/[\W_]+/g, "");
stringB = stringB.toLowerCase().replace(/[\W_]+/g, "");
const stringASorted = stringA.split("").sort().join("");
const stringBSorted = stringB.split("").sort().join("");
return stringASorted === stringBSorted;
}
Example 4: java anagrams
static boolean isAnagram(String a, String b) {
String sortedA = "";
Object[] aArr = a.toLowerCase().chars().sorted().mapToObj(i -> (char) i).toArray();
for (Object o: aArr) {
sortedA = sortedA.concat(o.toString());
}
String sortedB = "";
Object[] bArr = b.toLowerCase().chars().sorted().mapToObj(i -> (char) i).toArray();
for (Object o: bArr) {
sortedB = sortedB.concat(o.toString());
}
if(sortedA.equals(sortedB))
return true;
else
return false;
}