我正在嘗試創建一個靜態方法「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));
}
謝謝回答大家,但我忘了提,我試圖做一個靜態方法「indexOfKeyword」使用佛羅里達州的例子是行不通的 – Oninez 2014-10-28 02:40:34