Java 8 – How to find First and Last index of particular character or sub-string in a String ?

In this article, we will understand with a Java program on how to find First & Last index of particular character or sub-string in a String using Java 1.8 version

Already in one of the previous article, we discussed how to find First index and Last index of a character/sub-string in a String

Find First and Last index of character/sub-string :

  • indexOf() method of String
    • This String method is used to get 1st index of specified character/sub-string from the invoking string
    • Forward-searching :- This will start searching specified element from the beginning to the end (left-to-right scanning)
    • Read Java – String indexOf() method for more details
    • There are 4 variants of indexOf() method,

Method Signature:

public int indexOf(int ch);
public int indexOf(int ch, int fromIndex);
 
public int indexOf(String str);
public int indexOf(String str, int fromIndex);
  • lastIndexOf() method of String
    • This String method is used to get last index of specified character/sub-string from the invoking string
    • Backward-searching :- This will start searching specified element from the end to the beginning (right-to-left scanning)
    • Read Java – String lastIndexOf() method for more details
    • There are 4 variants of lastIndexOf() method,

Method Signature:

public int lastIndexOf(int ch);
public int lastIndexOf(int ch, int fromIndex);
 
public int lastIndexOf(String str);
public int lastIndexOf(String str, int fromIndex);

FirstAndLastIndexOfString.java

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

import java.util.stream.Stream;

public class FirstAndLastIndexOfString {

	public static void main(String[] args) {

		// test string
		String str = "BenchResources";


		// 1. find 1st index of character 'R'
		int indexR = Stream
				.of(str)
				.map(s -> s.indexOf('R'))
				.findAny()
				.get();
		System.out.println("First index of 'R' is = " + indexR);


		// 2. find 1st index of sub-string "source"
		int indexSource = Stream
				.of(str)
				.map(s -> s.indexOf("source"))
				.findAny()
				.get();
		System.out.println("First index of \"source\" is = " + indexSource);


		// 3. find last index of character 'e'
		int indexE = Stream
				.of(str)
				.map(s -> s.lastIndexOf('e'))
				.findAny()
				.get();
		System.out.println("Last index of 'e' is = " + indexE);


		// 4. find last index of sub-string "Ben"
		int indexBen = Stream
				.of(str)
				.map(s -> s.lastIndexOf("Ben"))
				.findAny()
				.get();
		System.out.println("Last index of \"Ben\" is = " + indexBen);
	}
}

Output:

First index of 'R' is = 5
First index of "source" is = 7
Last index of 'e' is = 12
Last index of "Ben" is = 0

Related Articles:

References:

Happy Coding !!
Happy Learning !!

Java 8 - How to get hashCode of a String ?
Java 8 - How to join List of String elements using different delimiter ?