Check If a substring is in a string ignoring uppercase, lowercase and special characters?

Mimi Ashv :

I'm trying to check if a phrase like "Homemade Pizza!" contains a string like "pizza", BUT I want it to always be true, it doesn't matter if it's Pizza or pizza or Pizza! or pizza!

I'll explain the code:

recipesFounded is an array that contains the title, description, etc. That's why I put recipesFounded.get(i).getTitle().

The problem is that I have the "Homemade Pizza!" string, so If I search "Pizza!" it's good because the recipe is added in the trueOnes new recipe list , but if I search pizza (without mayus P and !) it doesn't.

The word is the string that I want to search (pizza, Pizza!...)


for (int i=0; i < recipesFounded.size(); i++) {
    if (recipesFounded.get(i).getTitle().contains(word)) {
       trueOnes.add(recipesFounded.get(i));
    }
}
WJS :

Use the toLowerCase method of String


word = word.replaceAll("[^a-zA-Z]","").toLowerCase(); // keep only letters

Per Andreas suggestion, convert word to lower case before looping. It is more efficient.

for (int i=0; i < recipesFounded.size(); i++) {
    if (recipesFounded.get(i).getTitle().toLowerCase()
              .contains(word)) {
       trueOnes.add(recipesFounded.get(i));
    }
}

Since List implements the iterable interface, you can do it like this. It presumes that you are using a class called Recipe

for (Recipe recipe : recipesFounded) {
    if (recipe.getTitle().toLowerCase()
            .contains(word)) {
       trueOnes.add(recipe);
    }
}

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=18597&siteId=1