Check if two Strings are anagrams or not in Java

//Here the main concept is to add the ascii values and if they are same then the strings are anagrams else not

import java.util.*;

public class anagrams {

public static void main(String [] args){

String a = “madam”;

String b = “damma”;

int sum1 =0;

int sum2=0;

char[] c = a.toCharArray();

char[] d = b.toCharArray();

if(c.length == d.length)

{

for (int i =0; i < c.length ; i++)

{

sum1 += c[i];

sum2 += d[i];

}

if(sum1 == sum2){

System.out.println(“They are anagrams”);

}

else{

System.out.println(“They are not”);

}

}

else{

System.out.println(“They are not”);

}

Arrays.sort(c);

Arrays.sort(d);

if(Arrays.equals(c, d) )

{

System.out.println(“They are anagrams”);

}

else{

System.out.println(“They are not “);

}

}

}

Advertisements

One thought on “Check if two Strings are anagrams or not in Java

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s