【问题标题】:Java String.contains() not working properlyJava String.contains() 无法正常工作
【发布时间】:2021-05-11 06:10:58
【问题描述】:

我正在使用主题标签在我的应用中实现搜索。这个想法是程序将循环我的数据库中的所有现有帖子并检查是否是 currentPost 中的所有输入主题标签,然后它将帖子添加到 recyclerView

由于某种原因,string.contains 无法正常工作,例如我搜索了“brasil historia”并且有两个主题标签,但函数返回为 false

这是我正在使用的方法:

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;

    }

这是我为 Log.i 获得的日志:

正如你在这里看到的,搜索字符串是“brasilhistoria”,它搜索了巴西和历史,但包含是错误的

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

【问题讨论】:

  • 您的标签似乎包含空格。

标签: java string list contains


【解决方案1】:

currentTag 后面有空格,然后调用例如:

"brasilhistoria".contains("brasil ");

答案是假的

【讨论】:

    【解决方案2】:

    标签中有尾随空格。在search: brasilhistoria currentTag: brasil counter: 0 中查看brasilcounter 之间的双空格!这意味着在这种情况下currentTag 不是brasil,而是brasil brasil 不包含在brasilhistoria 中。

    解决方案:trim 标记在某些时候删除尾随空格。

    【讨论】:

    • 嗨!这个空间实际上来自日志。我像这样从日志中删除了空间:Log.i("checkTags", "search: " + searchString + " currentTag:" + currentTag); ,现在它显示如下:I/checkTags: search: slides currentTag:slides I/checkTags: search string contaiins? false 所以这不是问题所在。有什么想法吗?
    • @Nina 不,有两个空格,一个来自日志语句,另一个来自currentTag。你可以例如记录标签的长度以查看它,或将其封装在' 中以查看currentTag 的实际边界。在您最新的日志语句中,尾随空白被“隐藏”了,因为该行在此处结束,因此您看不到像以前那样的空白。
    • 嗨!真的有空间!我只能看到它的长度!感谢您的帮助!
    猜你喜欢
    • 2017-02-17
    • 2017-03-30
    • 2015-02-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-02-20
    • 2011-08-26
    相关资源
    最近更新 更多