indexOf() Method In Java

indexOf method in java returns the position of character from a string. If the character is found it returns the position of the character and return -1 if not found in a string.

There are 4 types of indexOf method in java

  1. indexOf(int ch): It returns the index of a given character
  2. indexOf(int ch, int fromIndex): return the index of a given character from the given index.
  3. indexOf(String str): This method returns the index position of a substring from a string.
  4. indexOf(String str, int fromIndex): returns the index position of a substring from the given index.

Parameters

ch: a single character i.e ‘a’ , ‘h’.
fromIndex: This is the position that starts the search from.
substring: string to search within a string.

indexOf(int ch) Method Example

public class S4GExample {
	public static void main(String[] args) {
		String str="study4geeks";  
                // returns the index of character
		System.out.println(str.indexOf('e'));
                // returns the index of character
		System.out.println(str.indexOf('4'));
	}
}

output:

7
5

indexOf(int ch, int fromIndex) Example

public class S4GExample {
	public static void main(String[] args) {
		String str="study4geeks";  
		String str1="thisisdemo";  
		/*returns the index of the 
		 character from first index*/
		System.out.println(str.indexOf('s',1));
		/*returns the index of the 
		 character from 3th index*/
		System.out.println(str1.indexOf('i',3));
	}
}

output:

10
4

indexOf(String str) Example

public class S4GExample {
	public static void main(String[] args) {
		String str="study4geeks is a best website";  
		// returns the index of the substring
		System.out.println(str.indexOf("is"));
		// returns the index of the substring
		System.out.println(str.indexOf("best"));
	}
}

output:

12
17

indexOf(String str, int fromIndex) Example

public class S4GExample {
	public static void main(String[] args) {
		String str="study4geeks is is a best best website";  
		/*returns the index of the 
		 substring from 13th index*/
		System.out.println(str.indexOf("is",13));
		/*returns the index of the 
		 substring from 21th index*/
		System.out.println(str.indexOf("best",21));
	}
}

output:

15
25
Do you know?
indexOf() Method In Java This article is contribute by Study4Geeks If you want share your knowledge on Study4Geeks then go to login section.