Java Program to Check if Two Strings are Anagram - The Coding Shala
Hey there, welcome back to another post. In this post, we will learn how to check if two strings are anagram or not in Java.
Java Program to Check if Two Strings are Anagram
Two strings are called anagrams if one string can be converted to another string by rearranging the characters of the first string. For example:
String a = "race" and String b = "care" are anagrams, because from string "race" we can make the string "care".
By using the below ways, we can check if two strings are anagram or not:
- Convert strings to char arrays then sort the arrays.
Java Example to Check if Two Strings are Anagram using Sorting
Strings are anagram if the below conditions are true:
- The length of both strings should be the same.
- Characters and their frequencies should be the same in both the string.
We can convert both the strings to char array. After sorting the arrays we can check if both the array are the same or not.
Java Program:
import java.util.Arrays; /** * https://www.thecodingshala.com/ */ public class Main { public static boolean isAnagram(String str1, String str2) { if (str1.length() != str2.length()) { return false; } // convert to lower case and then char array char[] charArr1 = str1.toLowerCase().toCharArray(); char[] charArr2 = str2.toLowerCase().toCharArray(); // sort both arrays so we can compare Arrays.sort(charArr1); Arrays.sort(charArr2); // compare and return // we can compare using for loop or equals() method return Arrays.equals(charArr1, charArr2); } public static void main(String[] args) { String str1 = "Race"; String str2 = "care"; if (isAnagram(str1, str2)) { System.out.println(str1 + " and " + str2 + " are anagram."); } else { System.out.println(str1 + " and " + str2 + " are not anagram."); } } }
Output:
Race and care are anagram.
Other Posts You May Like
- Java Program to Check if a String is a Palindrome
- Java Program to Reverse a String
- Java Program to Find the Frequency of Characters in String
- Java Program to Right Rotate an Array
- Java Program to Reverse an Array
Please leave a comment below if you like this post or found some errors, it will help me to improve my content.
Comments
Post a Comment