lastIndexOf() StringBuffer Example


java.lang.StringBuffer class comes with many helper methods to manipulate string. One of the methods is overloaded lastsIndexOf() method used to search for the last occurrence of a stirng in the buffer.

What Java API says abou lastIndexOf() StringBuffer:

  • public int lastsIndexOf(String searchString): Returns an int value of the last occurrence of the index number of searchString in the buffer. Returns -1 if the searchString is not found.
  • public synchronized int indexOf(String searchString, int searchIndex): Returns an int value of the index number of the nearest occurrence of searchString in the buffer where search starts from searchIndex. Returns -1 if the searchString is not found.
Example on lastIndexOf() StringBuffer uses both overloaded methods
public class Demo
{
  public static void main(String args[])
  {					    // hello comes in 3 places	
   StringBuffer sb1 = new StringBuffer("123hello456hello789hello");    
			                    // to find last occurrence of hello
   int x = sb1.lastIndexOf("hello");   
   System.out.println("Last Occurrence of hello: " + x);

	// to find last occurrence of hello starting from 9th index number
   x = sb1.lastIndexOf("hello", 9);   
   System.out.println("Occurrence of hello from index 9: " + x);

   x = sb1.lastIndexOf("world");   	         // world does not exist
   System.out.println("Occurrence of world which does not exist: " + x);
 }
}
}


lastIndexOf() StringBuffer
Output screenshot on lastIndexOf() StringBuffer

Also know the usage of overloaded IndexOf() method which checks the starting index in the string.

Leave a Comment

Your email address will not be published.