Java String indexOf() Method Example

1. Overview

In this tutorial, We will learn about String indexOf() method with example on how to check whether the specified character is present in the input string or not.

Java String indexOf() Method Example


2. indexOf method


indexOf method returns index of the first occurrence of the given character even though it appears multiple times in the string.

This method is overloaded and has 4 versions.

public int indexOf​(int ch): Returns the index of first occurrence of character from given string.

public int indexOf​(int ch, int fromIndex):
It returns the index of first occurrence of character in the given string after the specified fromIndex. For example, if the indexOf() method is called like str.indexOf(‘A’, 5) then it would start looking for the character 'A' in string str after the index 5.

int indexOf(String str): Returns index of first occurrence of str from given string.

public int indexOf​(String str, int fromIndex): Returns the index within this string of the first occurrence of the specified substring, starting at the specified index.

3. indexOf Example

Example program on all 4 version of this method.

String str = "Hello Friend, I am glad to see you here my Friend";

// indexOf(int ch)
int index = str.indexOf('l');
System.out.println("indexOf(int ch) example : "+index);

// indexOf​(int ch, int fromIndex)
index = str.indexOf('l', 6);
System.out.println("indexOf(int ch, int fromIndex) example : "+index);

// indexOf(String str)
index = str.indexOf("Friend");
System.out.println("indexOf(String str) example : "+index);

// indexOf​(String str, int fromIndex)
index = str.indexOf("Friend", 15);
System.out.println("indexOf(String str, int fromIndex) example : "+index);

Output:

indexOf(int ch) example : 2
indexOf(int ch, int fromIndex) example : 20
indexOf(String str) example : 6
indexOf(String str, int fromIndex) example : 43


4. Conclusion


In this short article, We've seen how to find the given string or character is present in the string or not. And also seen start searching for the specified character from certain index on-wards.

Example program is implemented in this article is available on GitHub.

0 Comments