2014-09-05 16 views
1

所以我解析HTML,我試圖創建一個子字符串,從某個位置開始,然後停止941個字符。 Java中.substring方法的工作方式是您必須爲其提供一個起始位置和一個結束位置,但最終位置需要在啓動後成爲原始字符串上的一個位置。如何使用.substring方法從一個索引開始並獲取x個或其後的字符?

String html = "This is a test string for example"; 
html.substring(html.indexOf("test"), 6); 

這是我怎麼想的代碼工作的例子,它將使一個子開始在試驗和7個字符返回「測試字符串」後停止。但是,如果我使用這段代碼,我會得到一個indexOutOfBounds異常,因爲6在測試之前。工作代碼將如下

String html = "This is a test string for example"; 
html.substring(html.indexOf("test"), 22); 

這將返回「測試字符串」。但我不知道最後一個數字是什麼,因爲html總是在變化。所以問題是我該怎麼做才能開始一個特定的位置並在其後面結束x個字符?任何幫助將非常感激!謝謝!

+0

使用'+'(* on * indexOf結果)將提供有用的信息,'html.length()'也是如此,不管怎樣,不要手動解析HTML。 – user2864740 2014-09-05 01:43:57

+0

雅我在第一次使用這些信息時使用了這些信息,但第二天頁面又變得不一樣了,我的價值觀變得混亂了。 html.length()約爲50,000:/ – Cris 2014-09-05 01:54:45

回答

2

由於第二個參數是一個指標,而不是長度,你需要存儲的初始位置,長度增加了,像這樣:

String html = "This is a test string for example"; 
int pos = html.indexOf("test"); 
String res = html.substring(pos, pos+11); 

Demo.

+0

這非常合理!我現在就試試我,並讓你知道。萬分感謝! – Cris 2014-09-05 02:02:34

1

請參閱String.substring來源。

public String substring(int beginIndex, int endIndex) { 
    if (beginIndex < 0) { 
     throw new StringIndexOutOfBoundsException(beginIndex); 
    } 
    if (endIndex > value.length) { 
     throw new StringIndexOutOfBoundsException(endIndex); 
    } 
    int subLen = endIndex - beginIndex; 
    if (subLen < 0) { 
     throw new StringIndexOutOfBoundsException(subLen); 
    } 
    return ((beginIndex == 0) && (endIndex == value.length)) ? this 
      : new String(value, beginIndex, subLen); 
} 

在此源代碼(第8〜9行)中,第二個參數大於第一個參數。

你需要編輯這個。

String html = "This is a test string for example"; 
html.substring(html.indexOf("test"), (6+html.indexOf("test"))); 

希望能解決問題。

+0

這也是有道理的,也解決了我的問題。非常感謝您花時間回答,這非常聰明。我希望我能標出雙重正確的答案! – Cris 2014-09-05 03:34:56

相關問題