+ 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
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");
}
}
}
+ 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.
+ 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.
+ 4
def are_anagrams(str1, str2):
return sorted(str1) == sorted(str2)
print(are_anagrams("dog", "god")) # True
+ 1
hey Jeppz, thanks for sharing your code, its really helpful :D
+ 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#
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..
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