Java 8 – How to get sub-string from a String ?

In this article, we will understand with a Java program on how to get sub-string from a String using Java 1.8 version

Already in one of the previous article, we discussed how to get sub-string from a String

Get sub-string from a String :

  • substring() method of String
    • This String method returns substring for the specified begin value (start-index) and end value (end-index)
  • There are 2 variants or overloaded substring() methods, in addition to this there is subSequence() method which is very much same like 2nd variant but legacy and CharSequece
    • 1st variant – returns substring starting from specified index-position till length
    • 2nd variant – returns substring starting from specified index-position to specified end index-position
    • 3rd variant – returns substring starting from specified index-position to specified end index-position
  • Method signature of 3 variants are,

Method signature:

public String substring(int beginIndex);
 
public String substring(int beginIndex, int endIndex);
 
public CharSequence subSequence(int beginIndex, int endIndex);

GetSubstringFromString.java

package in.bench.resources.java8.string.methods;

import java.util.stream.Stream;

public class GetSubstringFromString {

	public static void main(String[] args) {

		// test string
		String str = "BenchResources";


		// 1st variant - specify only start index-position
		String subString1 = Stream
				.of(str)
				.map(s -> s.substring(5))
				.findAny()
				.get();
		System.out.println("Sub-string for starting with 5th index-position is = " 
				+ subString1);


		// 2nd variant - specify start/end index-position
		String subString2 = Stream
				.of(str)
				.map(s -> s.substring(7, 13))
				.findAny()
				.get();
		System.out.println("\nSub-string for starting-with 7th index & ending-with 12th index is = "
				+ subString2);


		// 3rd variant - specify start/end index-position
		CharSequence subSequence3 = Stream
				.of(str)
				.map(s -> s.subSequence(0, 5))
				.findAny()
				.get();
		System.out.println("\nSub-sequence for starting-with 0th index & ending-with 4th index is = "
				+ subSequence3);
	}
}

Output:

Sub-string for starting with 5th index-position is = Resources

Sub-string for starting-with 7th index & ending-with 12th index is = source

Sub-sequence for starting-with 0th index & ending-with 4th index is = Bench

Related Articles:

References:

Happy Coding !!
Happy Learning !!

Java 8 - How to merge/concatenate/join two lists into single list ?
Java 8 - How to get hashCode of a String ?