String method- indexof

indexof method is used to find out the index of a particular character or Substring into the String.

It has 4 type of different signatures.

  1. int indexOf(int ch)
  2. int indexOf(String str)
  3. int indexOf(int ch,int fromIndex)
  4. int indexOf(String str, int fromIndex)

We should know that index starts from number 0. Let’s see their implementation with examples.

int indexOf(int ch):

It returns the index of the first occurrence of character ch in a String.

public class ExampleIndexof {
	public static void main(String[] args) {

		String val1 = "Hello";
		System.out.println("index of char 'e' : "+val1.indexOf("e"));
	}

}
Output: index of char ‘e’ : 1

 

int indexOf(String str):

Returns the index of a substring in a String. We are searching the index of substring ‘World’ in a string ‘Hello World’.

public class ExampleIndexof {
	public static void main(String[] args) {

		String val1 = "Hello World";
		System.out.println("index of char 'World' : "+val1.indexOf("World"));
	}
}
Output: index of char ‘World’ : 6

 

int indexOf(int ch,int fromIndex):

It returns the index of first occurrence of character ch, starting from the specified index “fromIndex”. In the below example, we are finding the character ‘W’ in the String.

public class ExampleIndexof2 {
	public static void main(String[] args) {

		String val1 = "Hello World";
		System.out.println("index of char 'W' ,start from 4th position : "+val1.indexOf("W",3));
	}
}
Output: index of char ‘W’ ,start from 4th position : 6

 

int indexOf(String str, int fromIndex):

Returns the index of string str, starting from the specified index “fromIndex”.

public class ExampleIndexof {
	public static void main(String[] args) {

		String val1 = "How are you?";
		System.out.println("index of String 'Hello' ,start from 2nd position : "+val1.indexOf("are",1));
	}
}
Output: index of String ‘Hello’ ,start from 2nd position : 4
Ask Question
If you have any question, you can go to menu ‘Features -> Q&A forum-> Ask Question’.Select the desired category and post your question.
Avatar photo

Shekhar Sharma

Shekhar Sharma is founder of testingpool.com. This website is his window to the world. He believes that ,"Knowledge increases by sharing but not by saving".

You may also like...

1 Response

  1. August 6, 2015

    […] indexOf(String str, int fromIndex) […]