I am trying to see if a ArrayList of strings contains a word located in another string , but i am doing something wrong. Here is my code: Here is an example of my ArrayList
titles = {"Sodium " , " Lithium " , "Allura Red AC"};
String ocrRes = "I want some sugar , and some coffee with Allura Red AC , Ponceau 4R ";
for (int i = 0; i < titles.size() ; i++)
{
if (ocrRes.contains(titles.get(i)) )
{
ocrResult.setText(titles.get(i));
}
}
Any help will be much appreciated. Thank you in advance.
Here is an outline of how you would find a specific word in a string array:
String[] array;
//will return the index of the array where word found.
int checkWord(String searchWord)
{
for(int i = 0; i < array.length; i++)
{
if (searchWord.equals(array[i]))
return i;
}
}
You could implement something like this to find a word in your array, hope this helps :)
Your'e code seems to work fine... you probably didn't use the ArrayList as u should
use like this:
List<String> titles = new ArrayList<>();
titles.add("Sodium");
titles.add("Lithium");
titles.add("Allura Red AC");
String ocrRes = "I want some sugar , and some coffee with Allura Red AC , Ponceau 4R ";
for (int i = 0; i < titles.size() ; i++)
{
if (ocrRes.contains(titles.get(i)) )
{
ocrResult.setText(titles.get(i));
}
}
Edit:
Iv'e seen on your comments to other answeres u need another list with corresponding indexes so just create an array list the same why as I showed u in the code above...
Btw the the way u seem to init your list is like your initing an array which is different type and looks like this:
String[] array = {"Sodium " , " Lithium " , "Allura Red AC"};
gl
Here's another option using ListIterator
String ocrRes = "I want some sugar , and some coffee with Allura Red AC , Ponceau 4R ";
List<String> titles = Arrays.asList("Sodium", "Lithium", "Allura Red AC");
ListIterator<String> iterator = titles.listIterator();
while (iterator.hasNext()) {
String title = iterator.next();
if(ocrRes.contains(title)) {
System.out.println(title);
}
}
You can try this one. If a ArrayList of strings contains a word located in another String
. It will display the that String
only.
Sample Code
String str = "I want some sugar , and some coffee with Allura Red AC , Ponceau 4R ";
List<String> myList = Arrays.asList("Sodium", "Lithium", "Allura Red AC");
myList.forEach(new Consumer<String>() {
public void accept(String s) {
if(str.contains(s)) {
System.out.println(s);
}
}
});
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.