[英]Java String.contains() not working properly
我正在使用主題標簽在我的應用程序中實現搜索。 這個想法是程序將循環我的數據庫中的所有現有帖子並檢查是否是 currentPost 中的所有輸入主題標簽,然后它將帖子添加到 recyclerView
由於某種原因,string.contains 無法正常工作,例如我搜索了“brasil historia”並且有兩個主題標簽,但 function 返回為 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
您的currentTag
之后有空間,然后您調用例如:
"brasilhistoria".contains("brasil ");
答案是假的
標簽中有尾隨空格。 在搜索中查看brasil
和counter
之間的雙空格search: brasilhistoria currentTag: brasil counter: 0
! 這意味着在這種情況下currentTag
不是brasil
但brasil
和brasil
不包含在brasilhistoria
中。
解決方案:在某些時候trim
標簽以刪除尾隨空格。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.