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

Samual Sam
Samual Sam

Learning faster. Every day.

Updated on: 27-Jun-2020

532 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements