Categories
java String

find the first occurrence of a character in string using java

In this post, we will learn to find the first occurrence of a character in string using java

As like in above image we are going to take String “BeginnersBug” for our example.

This array starts from 0 index to 11.

In this example, we are going to find the first occurrence of character ‘e’. which is 1

Note: that indexOf is case sensitive. It will return -1 if the character is not found

Syntax
	int indexOf = s.indexOf('e');
Example
public class FirstOccurance {

	public static void main(String[] args) {
		try {
			String s = "BeginnersBug";
			int indexOf = s.indexOf('e');
			System.out.println("The first occurance of e is " + indexOf);
		} catch (Exception e) {
			e.printStackTrace();
		}

	}
}
Example
The first occurance of e is 1
Github

https://github.com/rkumar9090/BeginnersBug/blob/master/BegineersBug/src/com/geeks/example/strings/FirstOccurance.java

Related Articles

find the last index of a character in string using java