A word can be created from the characters of another words. That is called anagram. The word formation contains any combination of letters from other word. It may be scrambled or some phrases can be repeated.
Let us check the given strings are anagram or not in java
programming.
Logic:
isitAnagram() function:
- First, check for both strings length.
- Sort the characters in both arrays.
- Check whether both arrays are equal or not and return to the main() function.
main() function:
- Read two input strings from the user at run time.
- Call the isitAnagram() function.
- Receives the output from function and display the output.
Java Program to check for anagram:
import java.util.Arrays;
import java.util.Scanner;
//public class is created with member function
isitAnagram()
public class AnagramCheckEg {
public static
boolean isitAnagram(String st1, String st2) {
if
(st1.length() != st2.length()) {
return
false;
}
char[]
chArray1 = st1.toCharArray();
char[]
chArray2 = st2.toCharArray();
//Character
arrays are sorted
Arrays.sort(chArray1);
Arrays.sort(chArray2);
return
Arrays.equals(chArray1, chArray2);
}
//main() function
public static void
main(String[] args) {
Scanner myObj1
= new Scanner(System.in);
System.out.println("Enter the first String");
String string1
= myObj1.nextLine();
Scanner myObj2
= new Scanner(System.in);
System.out.println("Enter the second String");
String string2
= myObj2.nextLine();
//Function
call
if
(isitAnagram(string1, string2)) {
System.out.println("Yes. "+string1 + " and " +
string2 + " are anagrams.");
} else {
System.out.println("No. "+string1 + " and " +
string2 + " are not anagrams.");
}
}
}
Here is the output while executing the above program.
Output1:
C:\raji\blog>javac AnagramCheckEg.java
C:\raji\blog>java AnagramCheckEg
Enter the first String
java
Enter the second String
Programming
No. java and Programming are not anagrams.
Output2:
C:\raji\blog>javac AnagramCheckEg.java
C:\raji\blog>java AnagramCheckEg
Enter the first String
night
Enter the second String
thing
Yes. night and thing are anagrams.
This is the java implementation of anagram checking among
strings.Keep coding!!!!
No comments:
Post a Comment