Java – String indexOf() method

In this article, we will discuss different variants of index of methods to get first occurrence of character/substring using String’s indexOf() method

1. String’s indexOf() method:

  • This String method is used to get 1st index of specified/passed character/substring from invoking string
  • Note: There are 4 variants or overloaded indexOf() methods

1.1 Method Signature:

public int indexOf(int ch);
public int indexOf(int ch, int fromIndex);

public int indexOf(String str);
public int indexOf(String str, int fromIndex);

1.2 Parameters:

  • ch                 –> character to be searched, to get 1st occurrence
  • fromIndex  –> position from where search need to start
  • str                –> substring to be searched, to get 1st occurrence

1.3 Returns:

 indexOf() method Returns
indexOf(int ch)Returns 1st occurrence of specified character
indexOf(int ch, int fromIndex)Returns 1st occurrence of specified character, starting from specified index
indexOf(String str)Returns 1st occurrence of specified substring
indexOf(String str, int fromIndex)Returns 1st occurrence of specified substring, starting from specified index

2. Examples on indexOf() method:

  • Sample Java program to get 1st occurrence of specified character/substring using String’s indexOf() method

StringIndexOfMethod.java

package in.bench.resources.string.methods;

public class StringIndexOfMethod {

	public static void main(String[] args) {

		// sample string
		String str1 = "BenchResource.Net";

		// to get index of char 'R'
		int indexCh = str1.indexOf('R');

		// printing to console
		System.out.println("Index of char 'R' is : "
				+ indexCh);

		// to get index of char 'R',
		// starting from specified position
		int indexChfrom = str1.indexOf('r', 7);

		// printing to console
		System.out.println("Index of char 'r',"
				+ " starting from 7th position is : "
				+ indexChfrom);

		// to get index of substring 'Resource'
		int indexSubstring = str1.indexOf("Resource");

		// printing to console
		System.out.println("Index of substring 'Resource' is : "
				+ indexSubstring);

		// to get index of substring 'sour',
		// starting from specified pos
		int indexSubstringfrom = str1.indexOf("sour", 6);

		// printing to console
		System.out.println("Index of substring 'sour',"
				+ " starting from 6th position is : "
				+ indexSubstringfrom);
	}
}

Output:

Index of char 'R' is : 5
Index of char 'r', starting from 7th position is : 10
Index of substring 'Resource' is : 5
Index of substring 'sour', starting from 6th position is : 7

Related Articles:

References:

Happy Coding !!
Happy Learning !!

Java - 4 Ways to reverse a String
Java - String hashCode() method