簡體   English   中英

如何在整個字符串中搜索特定單詞?

[英]How to search the whole string for a specific word?

我有這個代碼,它搜索一個字符串數組並在輸入字符串匹配字符串的第一個字符時返回結果:

for (int i = 0; i < countryCode.length; i++) {
            if (textlength <= countryCode[i].length()) {
                if (etsearch
                        .getText()
                        .toString()
                        .equalsIgnoreCase(
                                (String) countryCode[i].subSequence(0,
                                        textlength))) {
                    text_sort.add(countryCode[i]);
                    image_sort.add(flag[i]);
                    condition_sort.add(condition[i]);
                }
            }
        }

但是我想在輸入字符串不僅匹配第一個字符而且匹配字符串中的任何位置的地方也獲取這些字符串? 這個怎么做?

您可以通過三種方法來搜索字符串是否包含子字符串:

String string = "Test, I am Adam";
// Anywhere in string
b = string.indexOf("I am") > 0;         // true if contains 

// Anywhere in string
b = string.matches("(?i).*i am.*");     // true if contains but ignore case

// Anywhere in string
b = string.contains("AA")  ;             // true if contains but ignore case

我沒有足夠的“聲譽點”在評論中回復,但接受的答案中有錯誤。 indexOf() 在找不到子字符串時返回 -1,所以它應該是:

    b = string.indexOf("I am") >= 0; 

試試這個-

etsearch.getText().toString().contains((String) countryCode[i]);

你可以使用包含。 如:

myString.contains("xxx");

另請參閱: http : //docs.oracle.com/javase/1.5.0/docs/api/java/lang/String.html ,特別是包含區域。

使用以下內容:

public boolean contains (CharSequence cs)

從:API 級別 1

確定此 String 是否包含傳遞的 CharSequence 中的字符序列。

Parameters

cs要搜索的字符序列。

Returns

如果此字符串中包含字符序列,則為true ,否則為false

實際上,android 中默認的 Arrayadapter 類似乎只是從整個單詞的開頭進行搜索,但是通過使用自定義 Arrayadapter 類,您可以搜索任意字符串的一部分。 我已經創建了整個自定義類並發布了庫。 這是非常容易使用。 您可以從此處或通過單擊下面提供的鏈接來檢查實施和使用情況。

https://github.com/mohitjha727/Advanced-Search-Filter

你可以參考這個簡單的例子——我們有名字“Mohit”和“Rohan”,如果我們輸入“M”,那么Mohit就會出現在搜索結果中,但是當我們輸入“oh”時,Mohit和Rohan都會出現在搜索結果中有共同的字母“哦”。

謝謝。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM