- Trending Categories
- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Java Program to check whether two Strings are an anagram or not.
According to wiki “An anagram is word or phrase formed by rearranging the letters of a different word or phrase, typically using all the original letters exactly once.”
To compare whether two strings are anagrams check if their lengths are equal? If so, convert these two strings into character arrays then, sort them and compare them using the sort() method of the Arrays class, if both are equal then given two strings are anagrams.
Example
import java.util.Arrays; public class AnagramSample { public static void main(String args[]) { String str1 = "recitals"; String str2 = "articles"; if (str1.length()==str2.length()) { char[] arr1 = str1.toCharArray(); Arrays.sort(arr1); System.out.println(Arrays.toString(arr1)); char[] arr2 = str2.toCharArray(); Arrays.sort(arr2); System.out.println(Arrays.toString(arr2)); System.out.println(Arrays.equals(arr1, arr2)); if(arr1.equals(arr2)) { System.out.println("Given strings are anagrams"); } else { System.out.println("Given strings are not anagrams"); } } } }
Output
[a, c, e, i, l, r, s, t] [a, c, e, i, l, r, s, t] true Given strings are not anagrams
Advertisements