Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if a List/ArrayList contains chars of a string Java

I want to check if a string is found in a given list filled with letters. For example , if i have :

ArrayList<String> list = new ArrayList();
list.add("a");
list.add("e");
list.add("i");
list.add("o");
list.add("u");

String str = "aeo";

for (int i = 0; i < list.size(); i++)
    for (int j = 0; j < str.length(); j++) {
        if (list.get(i).equals(str.charAt(j)))
            count++;
    }
System.out.println(count);

str is found in my letter list so I have to see my count having value 3 , because i've found 3 matches with the string in my list. Anyway, count is printed with value 0 . The main idea is that i have to check if str is found in the list no matter the order of the letters in str.

like image 310
lexraid Avatar asked Sep 14 '26 21:09

lexraid


2 Answers

You are comparing a String to a Character, so equals returns false.

Compare chars instead :

for (int i = 0; i < list.size(); i++) {
    for (int j=0; j < str.length(); j++) {
        if (list.get(i).charAt(0) == str.charAt(j)) {
            count++;
        }
    }
}

This is assuming your list contains only single character Strings. BTW, if that's the case, you would replace it with a char[] :

char[] list = {'a','e','i','o','u'};
for (int i = 0; i < list.length; i++) {
    for (int j = 0; j < str.length(); j++) {
        if (list[i] == str.charAt(j)) {
            count++;
        }
    }
}
like image 53
Eran Avatar answered Sep 16 '26 10:09

Eran


A string is not equals a character, so you have to convert the character to a string.

if (list.get(i).equals(String.valueOf(str.charAt(j))))

or the string to a char and compare it like that:

if (list.get(i).getCharAt(0)==str.charAt(j))
like image 38
Jens Avatar answered Sep 16 '26 11:09

Jens



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!