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