Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
230 views
in Technique[技术] by (71.8m points)

Comparing characters in 2 char Array using Java

I am a beginner in Java and I will like to know if there's a way to compare characters in a char Array with other characters in another char Array in order to see if they have characters that match. Not to see if they contain exactly the same characters in the same sequence as most examples explain.

For instance:

char [] word1= {'a','c','f','b','e'};

char[] word2= {'a','b','c','d','e','h','j','f','i','m'};

and using maybe if statements to say that word1 contains the characters in word2 so it is correct. Else it is incorrect if word2 is missing at least one character that word1 has.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

I created a little snippet and think it is what you are looking for:

public class Main {

    public static void main(String[] args) {
        char[] word1= {'a','c','f','b','e'};
        char[] word2= {'a','b','c','d','e','h','j','f','i','m'};
    
        System.out.println(Contains(word1, word2));
    }

    private static boolean Contains(char[] arr1, char[] arr2) {
        for (int i = 0; i < arr1.length; i++) {
            boolean containsChar = false;
            for (int j = 0; j < arr2.length; j++) {
                if (arr1[i] == arr2[j]) containsChar = true;
            }
            if (!containsChar) return false; // arr2 does not contain arr1[i]
        }
        return true;
    }

}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...