Java String indexOf()

Java String indexOf() Method

Java String IndexOf() method returns the position or index of the given character or substring. This method returns positive integer value when given character or substring has found. In the case of not found given character or substring, indexOf() returns a negative number.  

Note: index starts from 0 (Zero).

indexOf Java Types

There are four types of indexOf() method in Java. The Syntax of indexOf() methods are as follows:

int indexOf(int ch) : ch indicatess any character or unicode of particular
character.

int indexOf(int ch, int startFrom) : ch indicatess any character or unicode of particular character. startFrom indicates the start finding from given integer value. 

int indexOf(String str) :str indicates any string.

int indexOf(String str,int startFrom) : :str indicates any string.startFrom indicates the start finding from given integer value. 

Java indexOf() Example

1. In this example, we will give a character. This method will return the position of that character in the given string.

class IndexOfExample{
  public static void main(String []args){
    String fullStr = "DEVELOPER HELPS IS A PRORAMMING WEBSITE";
    System.out.println("Index of given character is:"+fullStr.indexOf('L'));
  }
}

Output :

Index of given character is:4

2. In Java String indexOf() example, we will give a character and starfrom value. This method will return the position of that character in the given string.

class IndexOfExample{
  public static void main(String []args){
  String fullStr = "DEVELOPER HELPS IS A PRORAMMING WEBSITE";
  System.out.println("Index of given character is:"+fullStr.indexOf('L',6));
  }
}

Output :

Index of given character is: 12

3. In this example, we will give a String. This method will return the position of that String in the given String.

class IndexOfExample{
  public static void main(String []args){
   String fullStr = "DEVELOPER HELPS IS A PRORAMMING WEBSITE";
   System.out.println("Index of given character is:"+fullStr.indexOf("LO"));
  }
}

Output :

Index of given character is:4

4. In this example, we will give a String and starfrom value. This method will return the position of that String in the given String.

class IndexOfExample{
 public static void main(String []args){
 String fullStr = "DEVELOPER HELPS IS A PRORAMMING WEBSITE";
 System.out.println("Index of given character is:"+fullStr.indexOf("EL",5));
 }
}

Output :

Index of given character is:11

More Related Post

Thanks for the reading post. I hope you like and understand the post. If you have any doubt regarding this post please comment below.

Leave a comment

Your email address will not be published. Required fields are marked *

0 0 0
FOLLOW ON