Search for a character from a given position in Java


Use the indexOf() method to search for a character from a given position.

Let’s say the following is our string.

String myStr = "Amit Diwan";

Here, we are searching for the character “i” in the string. We are beginning the index from 4 for our search.

int begnIndex = 4;
System.out.println("String: "+myStr);
strLastIndex = myStr.indexOf('i', begnIndex);

The following is the complete example.

Example

 Live Demo

public class Demo {
   public static void main(String[] args) {
      String myStr = "Amit Diwan";
      int strLastIndex = 0;
      int begnIndex = 4;
      System.out.println("String: "+myStr);
      strLastIndex = myStr.indexOf('i', begnIndex);
      System.out.println("The index of character a in the string beginning from index "+begnIndex+" ="+strLastIndex);
   }
}

Output

String: Amit Diwan
The index of character a in the string beginning from index 4 = 6

Samual Sam
Samual Sam

Learning faster. Every day.

Updated on: 26-Jun-2020

95 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements