Java String indexOf(String str) method with example

Java String indexOf(String str) method Returns the index within this string of the first occurrence of the specified substring. The returned index is the smallest value k for which: this.startsWith(str, k)
If no such value of k exists, then -1 is returned.

Method Signature

public int indexOf(String str)

Parameters:

str – the substring to search for.

Returns:

the index of the first occurrence of the specified substring, or -1 if there is no such occurrence.

String indexOf( String str) method internal implementation

public int indexOf(String str) {
        return indexOf(str, 0);
    }

indexOf(String str) method internally calls public int indexOf(String str, int fromIndex) method. Totally four variants of indexOf method there in Java String class.

  1. Java String indexOf(int ch) method with example
  2. Java String indexOf(int ch, int fromIndex) method with example
  3. Java String indexOf(String str) method with example
  4. Java String indexOf(String str, int fromIndex) method with example

Java String indexOf( String str) method example

package com.ehowtonow.java.lang.string;

public class IndexOfExample {

	public static void main(String[] args) {

		String s = "This is ehowtonow java tutorials";
		System.out.println("index of java : " + s.indexOf("java"));
		System.out.println("index of ehowtonow : "+ s.indexOf("ehowtonow"));
		System.out.println("index of tutorials : "+ s.indexOf("tutorials"));
	}

}

Output

index of java : 18
index of ehowtonow : 8
index of tutorials : 23


Ask your questions in eHowToNow Forum

Post your technical, non-technical doubts, questions in our site. Get answer as soon as possible, meanwhile you can help others by answering, unanswered questions.
To Ask new Question : Ask Question
Check our existing discussions : Questions & Answers

  1. Java String indexOf(String str) method with example
  2. How to get Character unicode point in a String
  3. How to convert a String to Lower case
  4. How to search a word inside String
  5. Java String indexOf(int ch, int fromIndex) method with example
  6. Java String codePointCount() method with example
  7. Java String Compare
  8. String Concatenation in Java
  9. How to format the String by using Locale
  10. Java String indexOf(int ch) method with example
  11. Java String compareTo() method with example
  12. How to find last occurrence of substring inside string
  13. Java String charAt() method with example
  14. How to Split the String in Java
  15. Remove the particular character from string

Be the first to comment

Leave a Reply

Your email address will not be published.


*