Google+

157. Using 'lastIndexOf( ) method with StringBuffer







lastIndexOf( ) method when used with StringBuffer searchers for the last occurrence of a substring in two formats and returns index value.

Example: (Search for the last occurrence of a substring from the beginning of the string till its end)

StringBuffer object1 = new StringBuffer("This is a test statement of a test person in a test environment");
object1.lastIndexOf("test"); -> It will search for the "test" substring from the beginning of the string "This is a test statement of a test person in a test environment" till the end of the string and give the index value of the last occurrence of the substring i.e. 47 in this example


Example: (Search for the last occurrence of a substring from beginning till the provided index of the string)

StringBuffer object1 = new StringBuffer("This is a test statement of a test person in a test environment");
object1.lastIndexOf("test",11); -> It will search for the "test" substring from beginning till the provided index 11 of the string "This is a test statement of a test person in a test environment"and give the index value of the last occurrence of the substring i.e. 10

Note: - IndexOf( ) and lastIndexOf( ) methods return '-1' as index value/result if the provided substring is not found in the string.


Lets implement this on Eclipse IDE:

1. Create 'lastIndexOfDemo' class  under any project as shown below:



2. Save and Run the 'lastIndexOfDemo' class
3. Observe that the output is displayed in the console as shown below:



Download this project:

Click here to download the project containing the class file used in this post (You can download this project and import into Eclipse IDE on your machine)




Please comment below to feedback or ask questions.

Using shortcuts for System.out.println( ) statement in Eclipse IDE will be explained in the next post. 





1 comment:

Sowmya said...

Hi Arun

After 157 post we should still go through the remaining post for Java?