+ 1

to check if two strings are anagrams in java

My code is working but giving me the wrong output. I tried but wasn't able to find the bug /*Determine if 2 Strings areanagramsof each other. What are anagrams? two equal length strings having same letters eg.- race and care */ package stringassignment; import java.util.Arrays; public class que4 { public static void main(String[] args) { String str1 = "earth"; String str2 = "heart"; if(str1.length() == str2.length()) { //converting the string to lowercase so to avaoid checking for uppercase seperately str1 = str1.toLowerCase(); str2 = str2.toLowerCase(); //making an array of char type char[] arraystr1 = str1.toCharArray(); char[] arraystr2 = str2.toCharArray(); //for sorting an array Arrays.sort(arraystr1); Arrays.sort(arraystr2); if(arraystr1.equals(arraystr2)) { System.out.println("these strings are anagrams"); } else { System.out.println("these strings are not anagrams"); } } } }

18th Dec 2022, 9:06 AM
RISHABH BHUTANI
RISHABH BHUTANI - avatar
3 odpowiedzi
+ 5
RISHABH BHUTANI Use Arrays.equals method Arrays.equals(arraystr1, arraystr2)
18th Dec 2022, 10:26 AM
A͢J
A͢J - avatar
+ 1
give us an example of output
18th Dec 2022, 10:00 AM
Huawei Smart
Huawei Smart - avatar
0
A͢J Huawei Smart it worked, as in my method I was comparing arrays using the method use to compare the string.......it was giving me the statement written in my else statement, because the if statement was not working
18th Dec 2022, 7:32 PM
RISHABH BHUTANI
RISHABH BHUTANI - avatar