Java String.contains()工作不正常
我正在用hashtags在我的应用程序中实现搜索。其思想是,程序将循环我的数据库中的所有现有帖子,并检查是否是currentPost中的所有输入hashtag,然后将帖子添加到recyclerView 由于某些原因,string.contains无法正常工作,例如,我搜索了“brasil historia”,发现两个hashtag都存在,但函数返回为false 这是我正在使用的方法:Java String.contains()工作不正常,java,string,list,contains,Java,String,List,Contains,我正在用hashtags在我的应用程序中实现搜索。其思想是,程序将循环我的数据库中的所有现有帖子,并检查是否是currentPost中的所有输入hashtag,然后将帖子添加到recyclerView 由于某些原因,string.contains无法正常工作,例如,我搜索了“brasil historia”,发现两个hashtag都存在,但函数返回为false 这是我正在使用的方法: private boolean checkTagsSearch(List<String> tags,
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;
}
标记中有尾随空格。请参见
search:brasilhistoria currentTag:brasil counter:0
中brasil
和counter
之间的双空格!这意味着在这种情况下,currentTag
不是brasil
,而是brasil
,并且brasil
不包含在brasilhistoria
中
解决方案:
trim
在某个点上删除标记,以删除尾随的空白。在currentTag
之后有空格,然后调用,例如:
"brasilhistoria".contains("brasil ");
答案为false您的标签似乎包含空格。您好!这个空间实际上来自日志。我删除了日志中的空格,如下所示:
log.I(“checkTags”,“search:+searchString+”currentTag:+currentTag”)代码>现在它显示如下:I/checkTags:search:slides currentTag:slides I/checkTags:search string contains?false
所以这不是问题所在。你知道还有什么吗?@Nina没有,有两个空格,一个来自log语句,另一个来自currentTag
。例如,您可以记录标记的长度以查看该长度,或者将其封装在”
中以查看当前标记的实际边界。在您最新的日志语句中,由于行结束于此,所以尾部空白被“隐藏”,因此您不会像以前那样看到空白。您好!真的有一个空间!我只能看到它的长度!谢谢你的帮助!
"brasilhistoria".contains("brasil ");