2013-07-24 61 views
1

你好,我在我的代碼,我得到一個錯誤的字符串索引超出範圍的java新:-21 我的代碼是字符串索引超出範圍:-21

String targetLexForRemaining=categoryWordStr.substring(categoryWordStr.indexOf("@@")+2,categoryWordStr.indexOf(" ")); 

在這行我出現錯誤? 我該怎麼做?

+4

當您運行的代碼是什麼'categoryWordStr'包含哪些內容? –

+1

1)*「plz help Thanx in advanced」*請爲'you','your','please'和'thanks使用正確的拼寫。這使人們更容易理解和幫助。 2)爲了更快地獲得更好的幫助,請發佈[SSCCE](http://sscce.org/)。 –

+0

categoryWordStr的大小小於21 – MayurB

回答

9

IndexOutOfBoundsException拋出如果beginIndex爲負,或者endIndex比該字符串對象的長度大,或beginIndexendIndex大。閱讀它的documentation

在致電subString方法之前,您應該檢查這些條件。

int beginIndex=categoryWordStr.indexOf("@@"); 
int endIndex=categoryWordStr.indexOf(" "); 

if(beginIndex!=-1 && beginIndex<=endIndex && endIndex<=categoryWordStr.length()) 
{ 
    //Call Substring 
} 
+0

非常感謝你的寶貴支持 – user2469963

2

我懷疑有一個空格(」「),比早先的‘@@’你要找的,這將陷入困境的第二個參數substring。如果你想獲得「@@和第一空間之間的文本」,那麼你應該使用的indexOf超載這需要一個起點:

int start = categoryWordStr.indexOf("@@"); 
// TODO: Validate that startisn't -1 
int end = categoryWordStr.indexOf(" ", start); 
// TODO: Validate that end isn't -1 
String targetLexForRemaining = categoryWordStr.substring(start + 2, end); 
相關問題