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