你好,我在我的代碼,我得到一個錯誤的字符串索引超出範圍的java新:-21 我的代碼是字符串索引超出範圍:-21
String targetLexForRemaining=categoryWordStr.substring(categoryWordStr.indexOf("@@")+2,categoryWordStr.indexOf(" "));
在這行我出現錯誤? 我該怎麼做?
你好,我在我的代碼,我得到一個錯誤的字符串索引超出範圍的java新:-21 我的代碼是字符串索引超出範圍:-21
String targetLexForRemaining=categoryWordStr.substring(categoryWordStr.indexOf("@@")+2,categoryWordStr.indexOf(" "));
在這行我出現錯誤? 我該怎麼做?
IndexOutOfBoundsException拋出如果beginIndex
爲負,或者endIndex
比該字符串對象的長度大,或beginIndex
比endIndex
大。閱讀它的documentation。
在致電subString
方法之前,您應該檢查這些條件。
int beginIndex=categoryWordStr.indexOf("@@");
int endIndex=categoryWordStr.indexOf(" ");
if(beginIndex!=-1 && beginIndex<=endIndex && endIndex<=categoryWordStr.length())
{
//Call Substring
}
非常感謝你的寶貴支持 – user2469963
我懷疑有一個空格(」「),比早先的‘@@’你要找的,這將陷入困境的第二個參數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);
當您運行的代碼是什麼'categoryWordStr'包含哪些內容? –
1)*「plz help Thanx in advanced」*請爲'you','your','please'和'thanks使用正確的拼寫。這使人們更容易理解和幫助。 2)爲了更快地獲得更好的幫助,請發佈[SSCCE](http://sscce.org/)。 –
categoryWordStr的大小小於21 – MayurB