简体   繁体   中英

Comparing character in two Strings

I want to check if the characters in each String are the same, and can I build a second String which is given from the characters from first String. For example I have Random String ="amksomsamk" and i have to compare it to another "askommmaks".

Firstly I write metod which check length

     public boolean areEquals(String s1, String s2){
        if (s1.toCharArray().length == s2.toCharArray().length){
            return true;
        }else
            return false;

and now I want to check each character in posible easy way. I will be grateful for your help

PS. For given example I want to get true in return because characters in this particular Strings are the same. amksomsamk a:2 m:3 k:2 s:2 o:1 askommmaks a:2 m:3 k:2 s:2 o:1 If i use equals it won't be working

Convert each String to char[]

char[] str1 = s1.toCharArray();
char[] str2 = s2.toCharArray();

Sort each char[]

Arrays.sort(str1);
Arrays.sort(str2);

Check if equal

return Arrays.equals(str1, str2);

You can compare it just using below function:

public boolean isEqual(String s1, String s2) {
    if (s1.length() != s2.length())
        return false;

    Map<Character, Integer> charsCountMap = getCharsByCount(s1);


    for (char c : s2.toCharArray()) {
        if (charsCountMap.get(c) == null)
            return false;

        charsCountMap.put(c, charsCountMap.get(c) - 1);
    }

    return charsCountMap.values().stream()
            .allMatch(count -> count == 0);
}

private Map<Character, Integer> getCharsByCount(String s) {
    Map<Character, Integer> charsCountMap = new HashMap<>(s.length());

    for (char c : s.toCharArray())
        charsCountMap.put(c, charsCountMap.getOrDefault(c, 0) + 1);

    return charsCountMap;
}

Using recursion with StringBuilder strings gives a terse solution, though it's not easy to understand the code:

public static void main(String[] args) {
    String s1 = "☆★👌\u4e16\u754c\u4f60d👉bbbZZ❸💋";
    String s2 = "Zb☆b\u754cb★👌👉\u4e16d❸\u4f60Z💋";
    boolean matched = (s1.length() != s2.length()) ? false : compareStrings(new StringBuilder(s1), new StringBuilder(s2));
    System.out.println("Same chars for '" + s1 + "' and '" + s2 + "'? " + matched);
}

private static boolean compareStrings(StringBuilder sb1, StringBuilder sb2) {
    if (sb1.length() == 0) {
        return true;
    }
    int ind = sb2.indexOf((String) sb1.subSequence(0, 1));
    return ind == -1 ? false : compareStrings(sb1.deleteCharAt(0), sb2.deleteCharAt(ind));
}

This is the output:

Same chars for '☆★👌世界你d👉bbbZZ❸💋' and 'Zb☆b界b★👌👉世d❸你Z💋'? true

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM