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.
- int indexOf(int ch)
- int indexOf(String str)
- int indexOf(int ch,int fromIndex)
- 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")); } }
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")); } }
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)); } }
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)); } }
1 Response
[…] indexOf(String str, int fromIndex) […]