JAVA PROGRAM
Check the given strings is anagram or not |Java Program|
Introduction
In this blog post, we will discuss how to check if two given strings are anagrams using a Java program. An anagram is a word or phrase formed by rearranging the letters of a different word or phrase, typically using all the original letters exactly once. For example, the strings "listen" and "silent" are anagrams.
Anagram
An anagram is a rearrangement of the letters of one word to form another word. For instance:
"army" and "mary"
"race" and "care"
Java Program to Check Anagrams
To determine if two strings are anagrams, we need to ensure that both strings contain the same characters with the same frequency. Below is a simple Java program that checks if two strings are anagrams.
Code
import java.util.Scanner;
public class AnagramChecker {
public static void main(String[] input) {
String str1, str2;
int len1, len2, i, j, found, not_found = 0;
Scanner scan = new Scanner(System.in);
System.out.println("Enter first string:");
str1 = scan.nextLine();
System.out.println("Enter second string:");
str2 = scan.nextLine();
len1 = str1.length();
len2 = str2.length();
if (len1 == len2) {
for (i = 0; i < len1; i++) {
found = 0;
for (j = 0; j < len2; j++) {
if (str1.charAt(i) == str2.charAt(j)) {
found = 1;
break;
}
}
if (found == 0) {
not_found = 1;
break;
}
}
if (not_found == 1) {
System.out.println("Strings are not anagram to each other.");
} else {
System.out.println("Strings are anagram.");
}
} else {
System.out.println("Strings are not anagram to each other.");
}
}
}
Output
Enter first string:
listen
Enter second string:
silent Strings are anagram.
How the Program Works
- Input Handling: The program starts by taking two input strings from the user.
- Length Check: It checks if the lengths of the two strings are equal. If not, they cannot be anagrams.
- Character Comparison: If the lengths are equal, it compares each character of the first string with every character of the second string.
- Anagram Verification: If all characters from the first string are found in the second string, it concludes that the strings are anagrams; otherwise, they are not.
Conclusion
The provided Java program offers a straightforward approach to check if two strings are anagrams. By understanding this basic method, you can explore more efficient and robust solutions to handle larger and more complex cases. Happy coding!
Post a Comment
0 Comments