Home>Article>Java> Java intercepts the last few characters of a string

Java intercepts the last few characters of a string

王林
王林 Original
2019-11-15 14:09:40 12739browse

Java intercepts the last few characters of a string

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

Because the character position of the string starts from 0, and the substring(int from, int to) method is closed in the front and open in the back, that is, [from, to), which can be understood as [from, to- 1]. At the same time, to can be omitted (polymorphism). By default, to intercepts the last digit of the string.

To intercept the last few characters in the string, you can first obtain the length of the string, and use the length-n of the string as the first parameter of the substring() method to intercept the string. The effect of the last n characters.

Example:

String str = "i like yanggb"; System.out.println(str.substring(str.length() - 6)); // yanggb

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

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

Recommended tutorial:Java tutorial

The above is the detailed content of Java intercepts the last few characters of a string. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn