java.lang.StringBuffer lastIndexOf(String str)

Syntax:

public int lastIndexOf(String str)

Java Code Example :

This java example source code demonstrates the use of lastIndexOf(String str) method of StringBuffer class. Initially the code assigns a string “javatutorialhq.com” as initial contents of the string buffer. Then we use the indexof method to get the last index on the stringbuffer object where we find the string “a”.

This is very useful to work with substring method of StringBuffer class. On this example we will also learn how to use the lastIndexOf method to work with substring.

package com.javatutorialhq.java.examples;

/*
 * This example source code demonstrates the use of 
 * lastIndexOf(String str) method of StringBuffer class
 */

public class StringBufferLastIndexOfString {

	public static void main(String[] args) {

		// initialize the StringBuffer object
		StringBuffer sb = new StringBuffer("javatutorialhq.com");
		System.out.println("Contents of buffer:" + sb);

		// get the index of "a" string from the stringbuffer object
		String str = "a";
		int index = sb.lastIndexOf(str);		
		System.out.println("index:" + index);
		// incorporate substring method
		String result = sb.substring(0, index);
		System.out.println("Results:" + result);

	}
}

Sample Output :

Running the above example source code will give the following output

lastIndexOf(String str) method example

lastIndexOf(String str) method example

Suggested Reading List :

References :