EN
Java - String substring() method example
5 points
Short example:
xxxxxxxxxx
1
// index - 012
2
String text = "abc";
3
4
System.out.println( text.substring(0) ); // abc
5
System.out.println( text.substring(1) ); // bc
6
System.out.println( text.substring(2) ); // c
7
System.out.println( text.substring(3) ); //
8
9
System.out.println( text.substring(0, 0) ); //
10
System.out.println( text.substring(0, 1) ); // a
11
System.out.println( text.substring(0, 2) ); // ab
12
System.out.println( text.substring(1, 2) ); // b
13
System.out.println( text.substring(1, 3) ); // bc
14
System.out.println( text.substring(0, 3) ); // abc
15
System.out.println( text.substring(2, 3) ); // c
16
System.out.println( text.substring(3, 3) ); //
In this post we cover usage of String substring() method with simple code examples.
We use Java String substring() method to get substring of given string based on provided indexes.
String substring with single parameter example.
int beginIndex - begin index is inclusive.
xxxxxxxxxx
1
public class Example1 {
2
3
public static void main(String[] args) {
4
5
// index - 012
6
String str = "abc";
7
8
System.out.println(str.substring(0)); // abc
9
System.out.println(str.substring(1)); // bc
10
System.out.println(str.substring(2)); // c
11
System.out.println(str.substring(3)); //
12
}
13
}
Output:
xxxxxxxxxx
1
abc
2
bc
3
c
4
String substring with 2 parameters example.
int beginIndex - begin index is inclusive
int endIndex - end index is exclusive
xxxxxxxxxx
1
public class Example2 {
2
3
public static void main(String[] args) {
4
5
// index - 012
6
String str = "abc";
7
8
System.out.println(str.substring(0, 0)); //
9
System.out.println(str.substring(0, 1)); // a
10
System.out.println(str.substring(0, 2)); // ab
11
System.out.println(str.substring(1, 2)); // b
12
System.out.println(str.substring(1, 3)); // bc
13
System.out.println(str.substring(0, 3)); // abc
14
System.out.println(str.substring(2, 3)); // c
15
System.out.println(str.substring(3, 3)); //
16
}
17
}
Output:
xxxxxxxxxx
1
2
a
3
ab
4
b
5
bc
6
abc
7
c
8
xxxxxxxxxx
1
public class Example3 {
2
3
public static void main(String[] args) {
4
5
// index - 0123456789
6
String str = "abcdefghij";
7
8
System.out.println(str.substring(0, 1)); // a
9
System.out.println(str.substring(0, 2)); // ab
10
System.out.println(str.substring(1, 2)); // b
11
System.out.println(str.substring(1, 3)); // bc
12
System.out.println(str.substring(0, 3)); // abc
13
System.out.println(str.substring(0, 4)); // abcd
14
System.out.println(str.substring(4, 7)); // efg
15
System.out.println(str.substring(4, str.length())); // efghij
16
System.out.println(str.substring(0, str.length())); // abcdefghij
17
18
// System.out.println(str.substring(-1, str.length()));
19
// when we use -1 index we will get below exception:
20
// StringIndexOutOfBoundsException: String index out of range: -1
21
}
22
}
Output:
xxxxxxxxxx
1
a
2
ab
3
b
4
bc
5
abc
6
abcd
7
efg
8
efghij
9
abcdefghij