2014-10-28 96 views
0

我正在嘗試創建一個靜態方法「indexOfKeyword」並返回一個indexOf字符串,其中的字符串未嵌入到另一個字中。如果沒有這種情況,它會返回-1。如何在另一個字符串中找到沒有嵌入另一個字詞的字符串?

例如,

String s = "In Florida, snowshoes generate no interest."; 
String keyword = "no"; 

這將返回31

我相信沒有被查找的字符串關鍵字的下一個出現的唯一問題。我至今是:

public static int indexOfKeyword(String s, String keyword) 
{ 

s = s.toLowerCase(); 
keyword = keyword.toLowerCase(); 


int startIdx = s.indexOf(keyword); 



while (startIdx >= 0) 
{ 

String before = " "; 
String after = " "; 

if (startIdx > 0){ 

    before = s.substring(startIdx - 1 , startIdx); 
} 


int endIdx = startIdx; 


if (endIdx < s.length()){ 

    after = s.substring(startIdx + keyword.length() , startIdx + keyword.length() + 1); 
} 


if (!(before.compareTo("a") >= 0 && before.compareTo("z") <= 0 && after.compareTo("a") >= 0 &&  after.compareTo("z") <= 0)){ 
    return startIdx; 
} 




startIdx = 
    /* expression using 2-input indexOf for the start of the next occurrence */ 

} 


    return -1; 
} 


public static void main(String[] args) 
{ 
// ... and test it here 
String s = ""; 
String keyword = ""; 

System.out.println(indexOfKeyword(s, keyword)); 
} 
+0

謝謝回答大家,但我忘了提,我試圖做一個靜態方法「indexOfKeyword」使用佛羅里達州的例子是行不通的 – Oninez 2014-10-28 02:40:34

回答

2

事情是這樣的:沒有嵌入另一個詞

String input = "In Florida, snowshoes generate no interest."; 
String pattern = "\\bno\\b"; 
Matcher matcher = Pattern.compile(pattern).matcher(input); 

return matcher.find() ? matcher.start() : -1; 

字符串不是用空格分隔的必然。它可以是逗號,句點,字符串的開頭等。

上述解決方案使用正則表達式的字邊界(\b)給出正確的解決方案。


如果有含正則表達式中使用時,是具有特殊含義的字符關鍵字的風險,你可能想先逃避它:

String pattern = "\\b" + Pattern.quote(keyword) + "\\b"; 

因此,一個完整的方法實現可能看起來像這樣的:

public static int indexOfKeyword(String s, String keyword) { 
    String pattern = "\\b" + Pattern.quote(keyword) + "\\b"; 
    Matcher matcher = Pattern.compile(pattern).matcher(s); 

    return matcher.find() ? matcher.start() : -1; 
} 
+1

值得向他展示如何將他的關鍵字轉化爲正則表達式 – 2014-10-28 02:41:27

+1

@KeithNicholas感謝您的幫助! – 2014-10-28 02:49:08

+1

+1我不得不說,我特別喜歡return語句,該語句整齊地調用'find()',它也*改變匹配器,允許'start()'立即被內聯調用。 – Bohemian 2014-10-28 02:53:33

相關問題