I'm getting StringIndexOutOfBoundsException when I try to reasign the value of a variable. protString = protString.substring(newRPos+1, input.length()); I understand that this is something I would rather not do... but as I don't know the index of newRPos I can't think of another way to iterate.

Thanks

Dani AI

Generated

Mixing lengths from two different strings is the most likely cause. If you call substring on protString but pass input.length() as the end index, that end index can exceed protString.length() and trigger the exception. pointed you toward a bounds check and rightly pointed at the String API; the practical follow-ups are to verify which string you mean to slice and to confirm the numeric bounds before calling substring.

Practical steps to diagnose and fix:

  • Log or inspect newRPos, protString.length() and input.length() at the moment just before the substring call.
  • Guard against newRPos == -1 (if it came from indexOf) and against negative values.
  • If you want the remainder of protString after newRPos, prefer the one-argument substring(beginIndex) or keep an explicit cursor instead of repeatedly reassigning the original string. Example pattern:
int cursor = newRPos + 1;
if (newRPos != -1 && cursor <= protString.length()) {
    String tail = protString.substring(cursor); // returns "" if cursor == length
    // process tail or advance cursor without mutating protString
}

If you perform many such slices in a loop, avoid repeated immutable-string allocations by tracking a cursor or using StringBuilder for in-place edits. See the Java String documentation and the StringBuilder class for exact behavior and performance notes: String (Java SE 8) javadoc and StringBuilder (Java SE 8) javadoc.

Recommended Answers

All 3 Replies

Then also check with if (newRPos < protString.length) . Also, is there any guarantee that input.length() is going to be larger than newRPos, as both of those are indexes (i.e. a start index and an end index) not a start and length, and I don't know how substring reacts if the end index is smaller than the start index..

... I don't know how substring reacts if the end index is smaller than the start index..

API doc states:

Throws: IndexOutOfBoundsException - if the beginIndex is negative, or endIndex is larger than the length of this String object, or beginIndex is larger than endIndex.

API doc states:

Thanks. That was just me being too lazy to look it up myself, and hoping the OP would figure out to do that. ;-)

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.