+ 5

How to check if two String are Anagram?

An anagram is a rearrangement of the letters in either a word or a phrase (using each letter exactly once in the word or phrase created). so how to check if two string are anagram? :D enjoy coding

1st Sep 2017, 3:24 AM
Hadi Kurniawan Sidiq
Hadi Kurniawan Sidiq - avatar
10 Réponses
+ 9
import java.util.Scanner; public class Anagram { public static void main(String[] input) { String str1, str2; int len, len1, len2, i, j, found=0, not_found=0; Scanner scan = new Scanner(System.in); System.out.print("Enter First String : "); str1 = scan.nextLine(); System.out.print("Enter Second String : "); str2 = scan.nextLine(); len1 = str1.length(); len2 = str2.length(); if(len1 == len2) { len = len1; for(i=0; i<len; i++) { found = 0; for(j=0; j<len; j++) { if(str1.charAt(i) == str2.charAt(j)) { found = 1; break; } } if(found == 0) { not_found = 1; break; } } if(not_found == 1) { System.out.print("Strings are not Anagram to Each Other..!!"); } else { System.out.print("Strings are Anagram"); } } else { System.out.println("number of characters in both strings should be same"); } } }
1st Sep 2017, 3:26 AM
P R
P R - avatar
+ 9
thanks Ace for correcting me here is the algo: 1.Enter two strings. 2.Check the length of both strings. (a) If equal goto step 3 (b) if Not equal print length of strings should be same goto step 4. 3. Compare both string if equal print anagram else not anagram. 4.Stop.
1st Sep 2017, 3:59 AM
P R
P R - avatar
+ 4
https://code.sololearn.com/cOh9M524FA8W/?ref=app My take on this written in Ruby. Done the way Ace suggested. Great excercise for learning string-manipulation.
1st Sep 2017, 4:42 AM
Jeppz
Jeppz - avatar
+ 4
def are_anagrams(str1, str2): return sorted(str1) == sorted(str2) print(are_anagrams("dog", "god")) # True
1st Sep 2017, 5:18 AM
David Ashton
David Ashton - avatar
+ 1
hey Jeppz, thanks for sharing your code, its really helpful :D
1st Sep 2017, 4:53 AM
Hadi Kurniawan Sidiq
Hadi Kurniawan Sidiq - avatar
+ 1
two texts are anagrams if they have the same length and each character in the first text exists in the second text the following code apply this algorithm in c#
1st Sep 2017, 5:11 PM
Rabee Abbas
Rabee Abbas - avatar
1st Sep 2017, 5:51 PM
Rabee Abbas
Rabee Abbas - avatar
0
Thanks, glad you liked it Hadi :D Noticed that it did not work if input had uppercase characters so i added a "downcase" before sorting. Probably a good idea to think about how to handle other characters like periods and commas as well..
1st Sep 2017, 5:23 AM
Jeppz
Jeppz - avatar
0
For Java: you can just compare lengths of both strings and if so (might trim() both) , sort them with the arrays.sort method and check afterwards. Not as complicated as the top comment is
1st Sep 2017, 10:22 PM
Katharina