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