java.lang.StringBuffer indexOf(String str)

Syntax:

public int indexOf(String str)

Java Code Example :

This java example source code demonstrates the use of indexOf(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 starting index of string “.com”.

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

package com.javatutorialhq.java.examples;

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

public class StringBufferIndexOfString {

	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 .com string from the stringbuffer object
		String str = ".com";
		int index = sb.indexOf(".com");
		System.out.println("index:" + index);
		// incorporate substring method
		String result = sb.substring(0, index);
		System.out.println("Result:" + result);

	}
}

Sample Output :

Running the above example source code will give the following output

indexOf(String str) method example

indexOf(String str) method example

Suggested Reading List :

References :