Today we will learn the Anagram program in Java and also learn the String Anagram Program in Java. But before starting you should have a little bit of knowledge about Anagram. So,
Table of Contents
What is Anagram Program in Java?
The two strings are called as Anagram of each other if they contain the same characters either arranged in sequence or not it is not necessary.
How to check two Strings are Anagram or not?
To check whether the given two strings are Anagram of each other or not the compiler will ask the user to enter the two strings to check. After the input given by the user, the program will start executing are check whether the strings are Anagram or not.
After executing the compiler will display the output. The two strings are Anagram if and only if characters in that strings are the same sequence is not mandatory.
For Example abcd and dcba, creative and reactive, course and source are Anagram of each other.
Anagram Algorithm:
1 Step: Declare two Strings.
2 Step: Find out the length of two Strings (Strings are not anagram if the length of strings is not the same).
3 Step: Even if the lengths are equal the two strings should be in lowercase because it makes easy to check.
4 Step: Now sort the characters in the strings.For, sorting convert the strings into a character array.
5 Step: After converting character array must be sorted.
6 Step: In the last step, the Anagram is checked.
There are different ways to check the Anagram program in Java we will see it one by one.
1. Anagram Program in Java Using Sorting
To check whether the strings are anagram of each other we have to use two java methods i.e sort( ) and equals( ).
First, we have to remove all the white spaces between the characters of the string. Then all the characters will be converted to the lower case so the case will be ignored while checking.
Now the strings are converted into a character array and then sorted using sort( ) method. After sorting we will compare both the strings using equals( ) method.
If it returns true then the two strings are an anagram of each other else not anagram of each other.
In this program, we have declared two strings abcd and cabd. Now, the program will check whether the two Strings are Anagram or not.
//learnprogramo import java.util.Arrays; import java.util.Scanner; public class learnprogramo { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); // Getting the input string from the user System.out.print("Enter the First String : "); String s1 = scanner.nextLine(); System.out.print("Enter the second String : "); String s2 = scanner.nextLine(); if(checkAnagram(s1, s2)) System.out.println(s1+" and "+s2+" are Anagrams"); else System.out.println(s1+" and "+s2+" are NOT Anagrams"); scanner.close(); } public static boolean checkAnagram(String s1, String s2) { // Remove all the white space s1 = s1.replaceAll("\\s", ""); s2 = s2.replaceAll("\\s", ""); // Check if both length matches if(s1.length() != s2.length()) return false; else { // Convert both Strings into lower case and into Character Array char[] arr1 = s1.toLowerCase().toCharArray(); char[] arr2 = s2.toLowerCase().toCharArray(); // Sort both Character Array Arrays.sort(arr1); Arrays.sort(arr2); // Check if both arrays are equal return (Arrays.equals(arr1, arr2)); } } }
Output:
2. Using Iterative Method
In this method, we check whether each character of the first string is situated in the second string. If the character is found then we remove that character from the second string and proceed to the next character.
And if the character is not found in the second string then the for loop is terminated. Then, we consider the given two strings are not an anagram of each other.
//Learnprogramo import java.util.Arrays; import java.util.Scanner; public class learnprogramo { static void isAnagram(String s1, String s2) { String copyOfs1 = s1.replaceAll("\\s", "").toLowerCase(); String copyOfs2 = s2.replaceAll("\\s", "").toLowerCase(); //Initially setting status as true boolean status = true; if(copyOfs1.length() != copyOfs2.length()) { status = false; } else { //Converting copyOfs1 to char array char[] s1ToArray = copyOfs1.toCharArray(); for (char c : s1ToArray) { int index = copyOfs2.indexOf(c); if(index != -1) { copyOfs2 = copyOfs2.substring(0, index)+copyOfs2.substring(index+1, copyOfs2.length()); } else { status = false; break; } } } //Output 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("Mother In Law", "Hitler Woman"); isAnagram("keEp", "peeK"); isAnagram("SiLeNt CAT", "LisTen AcT"); isAnagram("Toss", "Shot"); isAnagram("joy", "enjoy"); } }
Output:
3. Anagram Program in Java Using StringBuilder
This method is as same as the above method but, only the difference is that we ave used the java inbuilt method deletecharAt( ).
deletecharAt( ) method deletes the character from the second string if that character is present in the second string.
//Learnprogramo import java.util.Arrays; import java.util.Scanner; public class learnprogramo { static void isAnagram(String s1, String s2) { String copyOfs1 = s1.replaceAll("\\s", "").toLowerCase(); String copyOfs2 = s2.replaceAll("\\s", "").toLowerCase(); //Initially setting status as true boolean status = true; if(copyOfs1.length() != copyOfs2.length()) { status = false; } else { //Converting copyOfs1 to char array char[] s1Array = copyOfs1.toCharArray(); //Constructing StringBuilder from copyOfs2 StringBuilder sb = new StringBuilder(copyOfs2); //Checking whether each character of s1Array is present in sb for (char c : s1Array) { int index = sb.indexOf(""+c); if (index != -1) { //If present, removing that character from sb sb = sb.deleteCharAt(index); } else { status = false; break; } } } //Output 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("Mother In Law", "Hitler Woman"); isAnagram("keEp", "peeK"); isAnagram("SiLeNt CAT", "LisTen AcT"); isAnagram("Toss", "Shot"); isAnagram("joy", "enjoy"); } }
Output:
4. Using HashMap
To construct a HashMap we need Key and the Value. So, in this method, we will construct one object of HashMap where the character will be Key and the character occurrence as the value.
At first, we will increment the character count by 1. If the character is present in the first string and then decrement by 1 if that character is present in the second string.
In this way, we check the character count of the entire string. If any character count is not equal to zero, then both the string is not an anagram of each other.
//Learnprogramo import java.util.HashMap; import java.util.Scanner; public class learnprogramo { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); // Getting the input string from the user System.out.print("Enter the First String : "); String s1 = scanner.nextLine(); System.out.print("Enter the second String : "); String s2 = scanner.nextLine(); if (checkAnagram(s1, s2)) System.out.println(s1 + " and " + s2 + " are Anagrams"); else System.out.println(s1 + " and " + s2 + " are NOT Anagrams"); scanner.close(); } public static boolean checkAnagram(String s1, String s2) { if (s1.length() != s2.length()) return false; HashMap<Character, Integer> map = new HashMap<Character, Integer>(); for (int i = 0; i < s1.length(); i++) { char c = s1.charAt(i); if (map.containsKey(c)) map.put(c, map.get(c) + 1); else map.put(c, 1); } for (int i = 0; i < s2.length(); i++) { char c = s2.charAt(i); if (map.containsKey(c)) { if (map.get(c) == 1) map.remove(c); else map.put(c, map.get(c) - 1); } else return false; } if (map.size() > 0) return false; return true; } }
Output:
5. Anagram Program in Java Using X-OR
In this program, we will use the logic of XOR. Here, XOR returns bit by bit digits of XOR.
If XOR returns 1 then the bits are different and if XOR returns 0 then the bits are same.
//Learnprogramo import java.util.Scanner; public class learnprogramo { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); // Getting the input string from the user System.out.print("Enter the First String : "); String s1 = scanner.nextLine(); System.out.print("Enter the second String : "); String s2 = scanner.nextLine(); if (checkAnagram(s1, s2)) System.out.println(s1 + " and " + s2 + " are Anagrams"); else System.out.println(s1 + " and " + s2 + " are NOT Anagrams"); scanner.close(); } public static boolean checkAnagram(String s1, String s2) { // Remove all the white space, convert to lower case & character array char[] arr1 = s1.replaceAll("\\s", "").toLowerCase().toCharArray(); char[] arr2 = s2.replaceAll("\\s", "").toLowerCase().toCharArray(); if (arr1.length != arr2.length) return false; int xor = 0; for (int i = 0; i < arr1.length; i++) { xor ^= arr1[i] ^ arr2[i]; } return xor == 0? true: false; } }
Output:
6. Using ArrayList
In this method, each character of the string is added to the list and then whether both the lists are equal are checked.
//Learnprogramo import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.Scanner; public class learnprogramo { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); // Getting the input string from the user System.out.print("Enter the First String : "); String s1 = scanner.nextLine(); System.out.print("Enter the second String : "); String s2 = scanner.nextLine(); if (checkAnagram(s1, s2)) System.out.println(s1 + " and " + s2 + " are Anagrams"); else System.out.println(s1 + " and " + s2 + " are NOT Anagrams"); scanner.close(); } public static boolean checkAnagram(String s1, String s2) { s1 = s1.replaceAll("\\s", "").toLowerCase(); s2 = s2.replaceAll("\\s", "").toLowerCase(); if (s1.length() != s2.length()) return false; List<Character> list1 = new ArrayList<Character>(); List<Character> list2 = new ArrayList<Character>(); for (int i = 0; i < s1.length(); i++) { list1.add(s1.charAt(i)); } for (int i = 0; i < s2.length(); i++) { list2.add(s2.charAt(i)); } Collections.sort(list1); Collections.sort(list2); if (list1.equals(list2)) return true; else return false; } }
Output:
Conclusion:
So in this lesson, we have learned about the anagram program in C. If you have any doubt then please feel free to share it in the comment box given below.
Also Read:
- How to return an array in java.
- Convert int to string in java
- How to convert string to integer in java.
- 20 different star pattern programs in java.
- 20 different number pattern programs in java.
- How to reverse a string in java.
- Leap year program in Java.