indexOf(String str) and lastIndexOf(String str) String functions in java

indexOf(String str): Returns the index of the first occurrence of the specified substring within this string.

Syntax: 

public int indexOf(String str)

Note: If no such occurrence of substring within this string than it returns -1.
lastIndexOf(String str): Returns the index of the last occurrence of the specified substring within this string.

Syntax:

public int lastIndexOf(String str)

Note: If no such occurrence of substring within this string than it returns -1.

Example:

StringIndexTestExample.java

/**
 * This program is used to show the use 
 * of indexOf and lastIndexOf() method.
 * @author w3spoint
 */
class TestString{
	String str = "www.w3spoint.com";
 
	/**
	 * This method is used to show the use of indexOf() method.
	 * @author w3spoint
	 */
	public void indexOfTest(){
		System.out.println(str.indexOf("o"));
	}
 
	/**
	 * This method is used to show the use of lastIndexOf() method.
	 * @author w3spoint
	 */
	public void lastIndexOfTest(){
		System.out.println(str.lastIndexOf("o"));
	}
}
 
public class StringIndexTestExample {
	public static void main(String args[]){
		//creating TestString object
		TestString obj = new TestString();
 
		//method call
		obj.indexOfTest();
		obj.lastIndexOfTest();
	}
}

Output:

8
14

Download this example.
 
Next Topic: toLowerCase() and toUpperCase() String functions in java.
Previous Topic: startsWith(String prefix) and endsWith(String suffix) String functions in java.

 

Content Protection by DMCA.com
Please Share