Second Occurrence of Character in String in Java

In this post, I will be sharing how to find the second occurrence of a character in a string in Java with examples. We can easily achieve our goal of finding the second occurrence of a character in a given string using the indexOf() method.

Read Also: Find the last unique character of a string in Java

Let's dive deep into the topic:

Second Occurrence of Character in String in Java

1. Using indexOf(int ch, int fromIndex) method


We can find the second occurrence of a character in a string using the indexOf(int ch, int fromIndex) method in Java.

Syntax:


public int indexOf(int ch, int fromIndex)


Parameters:

ch - a character (Unicode code point).
fromIndex - the index to start the search from.

Returns:

According to Oracle docs, returns the index within this string of the first occurrence of the specified character, starting the search at the specified index. Returns -1 if the character does not occur.

Java Program:


public class SecondOccurrenceOfCharacter {
    public static void main(String args[]) {
      String str = "alive is awesome";
      char ch = 'i';
      int index = str.indexOf(ch, str.indexOf(ch) + 1);
      System.out.println("Index of the second occurrence of character '" + ch + "' in the given string is: " + index);
    }
}


Output:
Index of the second occurrence of character 'i' in the given string is: 6

Explanation:


Observe the first occurrence of the character 'i' in the index 2nd. As a result, the str.index(ch) returns value 2 which is passed to the previous method as a parameter. The str.indexOf(ch, 3) is called which returns the first occurrence of ‘o’ from the 3rd position hence the code returns 6.

That's all for today, please mention in the comments if you have any questions related to how to find the  second occurrence of a character in a string in Java with examples.

About The Author

Subham Mittal has worked in Oracle for 3 years.
Enjoyed this post? Never miss out on future posts by subscribing JavaHungry