Search code examples
javastringlistcontains

Java String.contains() not working properly


I am implementing a search in my app with hashtags. The idea is that the program will loop all existing posts in my databse and check if the is all the input hashtags in the currentPost and then it will add the post to the recyclerView

For some reason the string.contains is not working properly, for example I searched "brasil historia" and there are both hashtags, but the function return as false

This is the method I'm using:

private boolean checkTagsSearch(List<String> tags, String searchString, String query) {

        String[] searchHashtagsList = query.split(" ");
        int numberOfSearchedTags = searchHashtagsList.length;
        int counter=0;
        // if there is the search string in the tags
        // se o post tiver a search string
        for(String currentTag : tags){
            Log.i("checkTags", "search: " + searchString + " currentTag: " + currentTag+ " counter: "+counter);
            Log.i("checkTags", "search string contains? " + searchString.contains(currentTag));

            if (searchString.contains(currentTag)) {
                counter++;

                if(counter == numberOfSearchedTags) {
                    return true;
                }
            }
        }

        return false;

    }

Here is the Log I got for the Log.i:

As you can see in here the search string was "brasilhistoria" and it searched through brasil and historia, but the contains is false

2021-02-07 08:28:18.115 22455-22455/com.I/checkTags: search: brasilhistoria currentTag: brasil  counter: 0
2021-02-07 08:28:18.115 22455-22455/com.I/checkTags: search string contaiins? false
2021-02-07 08:28:18.115 22455-22455/com.I/checkTags: search: brasilhistoria currentTag: imperio  counter: 0
2021-02-07 08:28:18.115 22455-22455/com.I/checkTags: search string contaiins? false
2021-02-07 08:28:18.116 22455-22455/com.I/checkTags: search: brasilhistoria currentTag: primeiroreinado  counter: 0
2021-02-07 08:28:18.116 22455-22455/com.I/checkTags: search string contaiins? false
2021-02-07 08:28:18.116 22455-22455/com.I/checkTags: search: brasilhistoria currentTag: historia  counter: 0
2021-02-07 08:28:18.116 22455-22455/com.I/checkTags: search string contaiins? false

Solution

  • There are trailing whitespaces in your tags. See the double whitespace between brasil and counter in search: brasilhistoria currentTag: brasil counter: 0! That means the currentTag in that case was not brasil but brasil and brasil is not contained in brasilhistoria.

    Solution: trim the tags at some point to remove the trailing whitespaces.