java intercept last few characters in string

The String class in Java provides a substring(int from, int to) method for intercepting the characters from the position from to to-1 in the string.

Because the character position of the string starts from 0, and the substring(int from, int to) method is closed before and after, that is [from, to), which can be understood as [from, to-1].

At the same time, to can be omitted (polymorphism), and to is intercepted to the last digit of the string by default.

Then to intercept the last few characters in the string, you can first obtain the length of the string, and use the length of the string -n as the first parameter of the substring() method, you can realize the interception of the last n characters of the string. Effect.

String str = "i like yanggb";

System.out.println(str.substring(str.length() - 6)); // yanggb

Another thing to note is that String in Java is an immutable type, so the substring() method does not change the original string, but returns a new string.

System.out.println(str); // i like yanggb

 

"Do your best to do things right, and work hard to do things well."

Reprinted in: https://www.cnblogs.com/yanggb/p/11490105.html

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324849154&siteId=291194637
Recommended