Search for a character from a given position in Java

Java 8Object Oriented ProgrammingProgramming

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
raja
Published on 12-Dec-2018 14:41:26
Advertisements