Java – why link string Will trim () throw an exception?

Sorry, if this is 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 this number before the test

If I do:

str = str.substring(0,str.indexOf("test")).trim();
str = str.substring(str.lastIndexOf(" ")).trim();
System.out.println(str);

I see: "50"

But if I do this:

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

I get: exception Java in thread "main" Lang. stringindexoutofboundsexception: string index out of range: - 13

Why is this exception thrown because trim() returns a copy of the string and omits leading and trailing spaces? Why can't I link my method calls on STR? I can't understand

Solution

str = str.substring(0,str.indexOf("test")).trim().substring(str.lastIndexOf(" ")).trim();
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 methods are not the same

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>