Get the index of the first occurrence of a separator in Java

Java 8Object Oriented ProgrammingProgramming

We have the following string with two separators.

String str = "Tom-Hank-s";

We want the index of the first occurrence of the separator.

For that, you need to get the index of the separator using indexOf()

String separator ="-";
int sepPos = str.indexOf(separator);

The following is an example.

Example

 Live Demo

public class Demo {
   public static void main(String[] args) {
      String str = "Tom-Hank-s";
      String separator ="-";
      System.out.println("String: "+str);
      int sepPos = str.indexOf(separator);
      System.out.println("Separator's first occurrence: "+sepPos);
   }
}

Output

String: Tom-Hank-s
Separator's first occurrence: 3
raja
Published on 17-Dec-2018 11:11:35
Advertisements