EN
Java - get last 3 characters from string
0 points
In this article, we would like to show you how to get the last 3 characters from a string in Java.
Quick solution:
xxxxxxxxxx
1
String text = "1234";
2
String lastCharacters = text.substring(text.length() - 3);
3
4
System.out.println(lastCharacters); // 234
The below example shows how to use substring()
method to get the last 3
characters from the text
string.
StringUtils.java
file:
xxxxxxxxxx
1
public class StringUtils {
2
3
public static String getLastCharacters(String text, int charactersCount) {
4
int length = text.length();
5
int offset = Math.max(0, length - charactersCount);
6
return text.substring(offset);
7
}
8
9
public static void main(String[] args) {
10
11
System.out.println( getLastCharacters( "1234", 3) ); // 234
12
System.out.println( getLastCharacters( "123", 3) ); // 123
13
System.out.println( getLastCharacters( "12", 3) ); // 12
14
System.out.println( getLastCharacters( "1", 3) ); // 1
15
System.out.println( getLastCharacters( "", 3) ); //
16
}
17
}
Output:
xxxxxxxxxx
1
234
2
123
3
12
4
1