EN
Java - get last character from string
0 points
In this article, we would like to show you how to get the last character from a string in Java.
Quick solution:
xxxxxxxxxx
1
String text = "1234";
2
String lastCharacter = text.substring(text.length() - 1);
3
4
System.out.println(lastCharacter); // 4
The below example shows how to use substring()
method to get the last character 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", 1) ); // 4
12
System.out.println( getLastCharacters( "123", 1) ); // 3
13
System.out.println( getLastCharacters( "12", 1) ); // 2
14
System.out.println( getLastCharacters( "1", 1) ); // 1
15
System.out.println( getLastCharacters( "", 1) ); //
16
}
17
}
Output:
xxxxxxxxxx
1
4
2
3
3
2
4
1