Get the Index of the First Occurrence of a Separator in Java



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
Updated on: 2020-06-27T06:46:57+05:30

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements