Checking if 2 strings contain the same characters?

前端 未结 10 897
孤城傲影
孤城傲影 2020-12-10 04:49

Is there a way to check if two strings contain the same characters. For example,

abc, bca -> true
aaa, aaa -> true
aab, bba -> false
abc, def ->          


        
10条回答
  •  南方客
    南方客 (楼主)
    2020-12-10 05:33

    here:

        String str1 = "abc";
        String str2 = "cba";
        /* create sorted strings */
    
    /*  old buggy code
        String sorted_str1 = new String( java.utils.Arrays.sort(str1.toCharArray()) );
        String sorted_str2 = new String( java.utils.Arrays.sort(str2.toCharArray()) );
    */    
    /* the new one */
    char [] arr1 = str1.toCharArray();
    char [] arr2 = str2.toCharArray();
    java.utils.Arrays.sort(arr1);
    java.utils.Arrays.sort(arr2);
    String sorted_str1 = new String(arr1);
    String sorted_str2 = new String(arr2);
    
    if (sorted_str1.equals( sorted_str2 ) ) {
            /* true */
        } else {
            /* false */
        }
    

提交回复
热议问题