Why chaining on String.trim() throws Exception?

java, string

Solution

str = str.substring(0, str.indexOf("test")).trim().substring(str.lastIndexOf(" ")).trim();
                                                             ^

This `str` refers to the original string.

str = str.substring(0, str.indexOf("test")).trim();  // first operation
str = str.substring(str.lastIndexOf(" ")).trim();
                    ^

This `str` refers to the string after the first operation is applied. Therefore, the two approaches are not equivalent.

Problem

Sorry if it's a stupid question, but I can't find an explanation. I have a String like this : ``` String str ="This is 50 test. Try it !!"; ``` I want to get the number just before `test`. If I do : ``` str = str.substring(0, str.indexOf("test")).trim(); str = str.substring(str.lastIndexOf(" ")).trim(); System.out.println(str); ``` I get : `"50"` However if I do this : ``` str = str.substring(0, str.indexOf("test")).trim().substring(str.lastIndexOf(" ")).trim(); ``` I get : `Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: -13` Since `trim()` returns a copy of the string, with leading and trailing whitespace omitted, why this exception is thrown ? Why can't I chain my methods call on `str` ? I can't understand.

Original source