Ad Code

Responsive Advertisement

Ticker

6/recent/ticker-posts

Java Program To Find Whether Two Strings are Anagram of Each Other

Java Program which will tell you if two strings are anagram of each other.

Libraries used in this program - 

1) import java.io.* - This is used for all the Input and Output functions in a Java program.

2) import java.util.Arrays - The Array class provides the static methods to dynamically create and access the Java Arrays.

3) import java.util.Collections - It is the package that contains the Collections classes.

Program - 

import java.io.*;
import java.util.Arrays;
import java.util.Collections;

class anagram {

/* function to check whether two strings are
anagram of each other */
static boolean areAnagram(char[] str1, char[] str2)
{
// Get lenghts of both strings
int n1 = str1.length;
int n2 = str2.length;

// If length of both strings is not same,
// then they cannot be anagram
if (n1 != n2)
return false;

// Sort both strings
Arrays.sort(str1);
Arrays.sort(str2);

// Compare sorted strings
for (int i = 0; i < n1; i++)
if (str1[i] != str2[i])
return false;

return true;
}

/* Driver Code*/
public static void main(String args[])
{
char str1[] = { 't', 'e', 's', 't' };
char str2[] = { 't', 't', 'e', 's' };
// Function Call
if (areAnagram(str1, str2))
System.out.println("The two strings are" + " anagram of each other");
else
System.out.println("The two strings are not " + " anagram of each other");

}
}

Output - 
The two strings are anagram of each other

How this program works?
In this program we have used the static boolean areAnagram function to check whether the two strings are anagram of each other.
We have used the length function to get the length of the strings.
Arrays.sort method is used to sort the arrays. In the main method, we have declared the two strings.

Post a Comment

0 Comments

Ad Code

Responsive Advertisement