In Java, theString indexOf() method returns the position of the first occurrence of the specified character or string in a specified string. In this article, we will learn various ways to useindexOf() in Java.
Example:
Below is the simplest way thatreturnstheindexof thefirst occurrence of a specified character in a string, or -1 if the character does not occur.
Java// Java code to demonstrate the working of String indexOf()// using indexOf(char ch)publicclassIndex1{publicstaticvoidmain(Stringargs[]){Strings=newString("Welcome to geeksforgeeks");System.out.print("Found g first at position: ");System.out.println(s.indexOf('g'));}}OutputFound g first at position: 11
Explanation:
In the above example, it finds the first occurrence of the characterg in the string"Welcome to geeksforgeeks" and prints its index i.e. 11.
Different Variants of indexOf() Method in Java
There are3 variants of the indexOf() method are mentioned below:
1. indexOf(char ch, int strt)
This methodreturns the index of the first occurrence of the specified character by starting the search at the specified index.
Example:
Java// Java code to demonstrate the working of String indexOf(char ch, int strt)publicclassIndex2{publicstaticvoidmain(Stringargs[]){Strings=newString("Welcome to geeksforgeeks");System.out.print("Found g after 13th index at position: ");System.out.println(s.indexOf('g',13));}}OutputFound g after 13th index at position: 19
2. indexOf(String str)
This method returnsthe index of the first occurrence of the specified substring in the string.
Example:
Java// Java code to demonstrate the working of String indexOf(String str)publicclassIndex3{publicstaticvoidmain(Stringargs[]){Strings=newString("Welcome to geeksforgeeks");// Initializing search stringStrings1=newString("geeks");// print the index of initial character of SubstringSystem.out.print("Found geeks starting at position: ");System.out.print(s.indexOf(s1));}}OutputFound geeks starting at position: 11
3. indexOf(String str, int strt)
This method returnsthe index of the first occurrence of the specified substring by starting the search at the specified index.
Example:
Java// Java code to demonstrate the working of String indexOf(String str, int strt)publicclassIndex4{publicstaticvoidmain(Stringargs[]){Strings=newString("Welcome to geeksforgeeks");// Initializing search stringStrings1=newString("geeks");// print the index of initial character// of Substring after 14th positionSystem.out.print("Found geeks(after 14th index) starting at position: ");System.out.print(s.indexOf(s1,14));}}OutputFound geeks(after 14th index) starting at position: 19
Explore
Java Basics
OOP & Interfaces
Collections
Exception Handling
Java Advanced
Practice Java