Reputation: 105
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.
Upvotes: 3
Views: 14057
Reputation: 83
Convert the character to the string:
list.get(i).equals(String.valueOf(str.charAt(j)))
The correct syntax to convert character to the string is:
list.get(i).charAt(0) == str.charAt(j)
list.get(i).getCharAt(0)==str.charAt(j)
won't work as written in Jens' answer.
Upvotes: 1
Reputation: 393781
You are comparing a String
to a Character
, so equals
returns false
.
Compare char
s 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 String
s. 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++;
}
}
}
Upvotes: 5
Reputation: 105
Yes, this is right. Thanks for it . And I've also just checked now and saw that I could make my list :
ArrayList<Character> list ;
instead of
ArrayList<String> list ;
Upvotes: 0
Reputation: 22422
You can use streams
to get the answer in one line as shown below with inline comments:
ArrayList<String> list = new ArrayList();
//add elements to list
String str = "aeo";//input string
//split str input string with delimiter "" & convert to stream
long count = Arrays.stream(str.split("")).//splt the string to array
filter(s -> list.contains(s)).//filter out which one matches from list
count();//count how many matches found
System.out.println(count);
Upvotes: 1
Reputation: 69440
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))
Upvotes: 1